cmemoryintuint8tuint16

C int memory storage. Least signinficant vs most significant bits?


I'd expect the following combination of two uint8_t (0x00 and 0x01) into one uint16_t to give me a value of 0x0001, when I combine them consecutively in memory. Instead I obtain 0x0100 = 256, which I'm surprised of.

#include <stdio.h>
#include <stdint.h>

int main(void){

    uint8_t u1 = 0x00, u2 = 0x01;
    uint8_t ut[2] = {u1, u2};
    uint16_t *mem16 = (uint16_t*) ut;

    printf("mem16 = %d\n", *mem16);

    return 0;
}

Could anyone explain me what I've missed in my current understanding of C memory? Thank you! :-)


Solution

  • It is called endianess.

    Most system nowadays use little endian. In this system first is stored the least significant byte. So the 0x0100 is stored (assuming 2 bytes representation) as {0x00, 0x01} exactly as in your case