c++ - Unexpected results when casting dword to byte [4] (endianity swap?) -
im trying cast dword array of 4 bytes. when this, bytes seem flip around (change endianness)
as understand dword equaling 0x11223344 on little endian systems this:
0000_1011___0001_0110___0010_0001____0010_1100
but when this:
typedef unsigned long dword; typedef unsigned char byte; int main(void) { dword = 0x11223344; byte b[4]; memcpy(b, &a, 4); printf("%x %x %x %x\n", b[0], b[1], b[2], b[3]); }
i 44 33 22 11.
expected 11 22 33 44.
same thing happens when use reinterpret_cast or
union { dword a; byte b[4]; } foo;
im guessing im wrong , not compiler/processor, missing here? how on big endian system?
edit: guess understanding of little endian systems wrong. question: faster while still being portable: using shifts individual byte values or using memcpy/reinterpret_cast , htonl()/ntohl()?
no, understanding of little-endian incorrect. little endian means least significant byte @ lowest memory address.
also:
as understand dword equaling 0x11223344 on little endian systems this:
0000 1011 0001 0110 0010 0001 0010 1100
that bit pattern doesn't have 0x11223344
@ all, little or big endian. on little endian architecture, read
0100 0100 0011 0011 0010 0010 0001 0001
on big endian system, however, same be
0001 0001 0010 0010 0011 0011 0100 0100
Comments
Post a Comment