Search code examples
cendianness

How does little-endian processor save a number in their memory in C?


short a = 0x1234;
char *p = &a;
printf("%x%x", *p, *(p+1));

output
3412

I'm curious about how memory store a value 0x1234. I firstly thought 0x1234 is saved as 0x3412(reversed per byte) in memory, but according to lsb 0 numbering, it seems right that memory saves 0x1234 as 0x2c48(reversed per bit) I think that the value 0x1234 is saved in memory as 0x2c48 and little-endian cpu regards 0x2c48 as 0x1234. Is this correct?


Solution

  • On a little-endian system a multi-byte word is stored in reverse byte order.

    So e.g. the 16-bit word 0x1234 will be stored with 0x34 in the low address, and 0x12 in the high address.

    As a byte array it would be

    uint8_t word[2] = { 0x34, 0x12 };
    

    Bits of a byte are never reversed.


    A 32-bit (four byte) word like 0x12345678 would be stored in the order 0x78, 0x56, 0x34 and 0x12 (low to high address).