Paul Zhang
Paul Zhang

Reputation: 11

Why, when I convert char[] to int, do I get a byte-wise reversal

My code looks like:

char tDat[]={'a','b','c','d','e','f','g','h'};

printf("%d\n",*(int*)tDat);

The result that ends up being printed is 1684234849. Which when converted into binary is 1100100011000110110001001100001. When the binary is converted to text again,

I get: dcba.

To my understanding, all I've done is take tDat, originally a char*, and converted it to a int*, which, to me, means that de-referencing will now read 4 consecutive bytes instead of 1. Upon de-referencing however, I get an integer corresponding to the reverse of what I expected. Can someone explain why I didn't get abcd back again?

Upvotes: 1

Views: 239

Answers (1)

Ziffusion
Ziffusion

Reputation: 8923

This is because you happen to be on a machine that is little endian. Intel processors are.

What this means is that ints are stored in memory with the least significant byte first. In your example the LSB would be 'a', then 'b', then 'c', and the MSB would be 'd'. This corresponds to an int that looks like "dcba" when written by our numerical conventions.

Upvotes: 3

Related Questions