Typecast cross-platform compatibility
what I'm trying to do is append a binary integer into a string object. So far I have this:
int number = 5;
cppstring.append((char*)&number, 4);
It works fine on a x86 system with Windows, 开发者_如何学Gobut some people are saying its not cross-platform and is unsafe. What is the preferred method to do this?
The reason it's not portable is that ints are not always 4 bytes. For instance, the ILP64 data model uses 8-bytes ints. C99 only requires that ints are at least 2 bytes. Why do you need to do this, and what is the desired behavior if the size of the int is not 4 bytes?
It will always usually work, whatever platform you are on, if by working you simply mean "not crash". EDIT I missed the size
argument of string::append
, so it can actually crash or yield weird results because of a buffer underflow on platforms where int
s are not 4 bytes long.
However, you may observe different results based on the integer size and endianness of the platform your code runs on, which is bad if you want to share files created on a platform to another platform running the same program.
It depends on what you expect it to do. Windows (usually) operates on little-endian machines that have 32 bits integers, which means your code will append 05 00 00 00
to your string. However, on big-endian machines that also have 32 bits integers, your code will append 00 00 00 05
to the string. Worse, your code could run on platforms that have 16-bit big-endian integers, which would append 00 05
.
Depending on which behavior you want, it might be a good idea to implement a "less magical" way to append the bytes, like a for
loop that knows it wants to append 4 bytes in a little-endian fashion:
int number = 5;
for(int i = 0; i < 4; i++)
{
char numberByte = (number >> (8 * i)) & 0xFF;
cppstring.append(&numberByte, 1);
}
This way, you're sure results will be consistent across platforms since the code depends on neither the size of an integer nor the byte order.
精彩评论