objective-cc

Why is this uint32_t ordered this way in memory?


I'm learning about endianness, and i read that Intel processors usually are little-endian. Im on an Intel mac and thought i'd try it for myself to see it in action. I define a uint32_t and then try to print out the 4 bytes as they are ordered in memory.

uint32_t integer = 1027;
uint8_t * bytes = (uint8_t*)&integer;
printf("%04x\n", integer);
printf("%x%x%x%x\n", bytes[0], bytes[1], bytes[2], bytes[3]);

Output:

0403
3400

I expected to see the bytes either in reverse order (3040) or unchanged, but what's output is neither. What am i missing?

Im actually compiling it as Objective-C using Xcode if that makes any difference.


Solution

  • Because saving data occurs in unit of bytes (8 bits) in today's typical computers.

    In machines in which little endian is used, the first byte is 03, the second byte is 04, and the third and forth bytes are 00.

    The first digit in the second line 3 represents the first byte and the second digit 4 represents the second byte. To show bytes with 2 digits for each bytes, specify width to print in the format like

    printf("%02x%02x%02x%02x\n", bytes[0], bytes[1], bytes[2], bytes[3]);