Possible Duplicate:
Detecting endianness programmatically in a C++ program
I am working on a C++ project that requires that I know if the system is big endian or little endian.
I have come up with some code that I think would succeed at detecting this! However, this is my first time really programming like this, and I’d like to know whether or not this would actually work:
int fourbytesint = 0;//Initialize four bytes
((char*)&fourbytesint)[0] = 1;//Get the first byte of our four bytes
//(Pretend the int is an array of 4 bytes, get the first byte)
//Depending upon the endian, this will be a reasonably small number, or an unreasonably large number
if (fourbytesint > 1000)
{
cout << "Big endian!" << endl;
}
else
{
cout << "Little Endian!" << endl;
}
Also, I was taught by my instructor that char, in c++ can by used to store bytes. I am a little wary of this, as I know in languages like Java, char typically stores two byte Unicode characters.
Am I correct in using char as a byte in the above example?
Yes, your method of detection works. (although you may be able to write your code in an endian independent way, for example using
htonl()as Brian Roach suggests. This would also make your code work even when big endian and little endian aren’t the only options.)Yes,
charin C++ is one byte. By defintion sizeof(char) == 1Edit: as pointed out in the comments, it’s possible that sizeof(char)==sizeof(int). Your code would detect this as big endian. But the concept of endianness doesn’t make sense when the storage for a type doesn’t span multiple addressable locations. That is, since ‘big endian’ means that ‘sub units’ of the int are ordered such that the more significant ones come before the less significant ones, it doesn’t make sense to use that term for something that only has one ‘sub-unit’. Still, you could write your code for either branch such that it handles this case, and then it won’t matter.