Compatibility between Typecast platforms

what I am trying to do is add a binary integer to the string object. So far I have this:

int number = 5;
cppstring.append((char*)&number, 4);

      

It works fine on an x86 system with Windows, but some people say it is not cross platform and insecure. What's the preferred method for doing this?

+2


a source to share


2 answers


The reason it is not portable is because ints are not always 4 bytes. For example, the ILP64 data model uses 8 byte ints. C99 only requires ints to be at least 2 bytes. Why do you need this, and what is the desired behavior if the int size is not 4 bytes?



+3


a source


It will always work normally no matter what platform you are on, as long as at work you just mean "not a crash." EDIT I missed the argument size

string::append

so that it might actually confuse or give weird results due to buffer overflows on platforms that int

don't have 4 bytes.

However, you may see different results based on the integer size and endianness of the platform your code is running on, which is bad if you want to exchange files created on the platform to another platform using the same program.

It depends what you expect from it. Windows (usually) runs on little-endian machines with 32 bit integers, which means your code will append 05 00 00 00

to your string. However, on big-endian machines that are also 32-bit full, your code will append 00 00 00 05

to the string. Worse, your code can run on platforms with large 16-bit integers that will add 00 05

.



Depending on what behavior you want, it might be a good idea to implement a "less magical" way of adding bytes, like a loop for

that knows it wants to add 4 bytes in little-endian style:

int number = 5;
for(int i = 0; i < 4; i++)
{
    char numberByte = (number >> (8 * i)) & 0xFF;
    cppstring.append(&numberByte, 1);
}

      

This way, you are confident that the results will be consistent across platforms, since the code does not depend on integer size or byte order.

+1


a source







All Articles