Search code examples
cendianness

Why does assigning a hex value give big-endian equivalent value on a little-endian machine?


Here is a simple c statement:

uint32_t x = 0x04000000;

On my little endian machine I assumed x would equal 4. But instead it's 67108864.

So there must be something very basic that I don't understand. Could you help explain please?


Solution

  • uint32_t x = 0x04000000;
    

    This operation is machine endianness agnostic. 0x04000000 is a hex literal with the value 67'108'864 (decimal). This is true on any endianness.

    If you want to see the effects of endianness systems you need to fiddle with the underlying memory. E.g.:

    uint32_t x;
    memcpy(&x,  (const unsigned char[4]) {0x04u, 0, 0, 0}, 4);