-1

For example:

int main(int argc, char* argv[]){
    char a[4]={0,0,0,1};
    int *ia=(int *)a;
    printf("%d",ia[0]);
}

It prints 16777216 because it's 00000001 00000000 00000000 00000000 in binary. Why does it turn?

marcellnemeth
  • 27
  • 1
  • 3

1 Answers1

2

The Intel x86 and also AMD64 / x86-64 series of processors use the little-endian format. The least significant byte (LSB) value is at the lowest address. The other bytes follow in increasing order of significance. This is akin to right-to-left reading in hexadecimal order.

the order of bytes within each value is reversed in little-endian machines as the picture below illustrates: enter image description here

So when you write an array of chars with increasing memory address, you are writing byte by byte which is not affected by endianness of the machine, but when you are trying to read the entire 4 byte as a single integer value, its read backwards.

note that the order of values within an array is not effected by endianness of the machine, but only bytes within a single 'multi byte value' are reordered.

Read more at Wikipedia

Solid State
  • 114
  • 5