Im trying to cast a dword into an array of 4 bytes. When i do this, the bytes seem to flip around (change endianness)
As i understand it a dword equaling 0x11223344 on little endian systems will look like this:
0000_1011___0001_0110___0010_0001____0010_1100
but when i do this:
typedef unsigned long dword;
typedef unsigned char byte;
int main(void)
{
dword a = 0x11223344;
byte b[4];
memcpy(b, &a, 4);
printf("%x %x %x %x\n", b[0], b[1], b[2], b[3]);
}
I get 44 33 22 11.
I expected it to be 11 22 33 44.
The same thing happens when i use reinterpret_cast or
union
{
dword a;
byte b[4];
} foo;
Im guessing Im wrong and not the compiler/processor, but what am i missing here? Also how would this look on a big endian system?
Edit: So i guess my understanding of little endian systems was wrong. Another question: which would be faster while still being portable: using shifts to get the individual byte values or using memcpy/reinterpret_cast and then htonl()/ntohl()?
No, your understanding of little-endian is incorrect. Little endian means that the least significant byte is at the lowest memory address.
Also:
That bit pattern doesn't have anything to do with
0x11223344
at all, be it little or big endian. On a little endian architecture, it would readOn a big endian system, however, the same would be