I created some simple code to test casting a char array to int pointer. This works fine as I expected, but when I wrote to the array using the pointer, the data got swapped MSB<-->LSB when I print the c array back out. Why does this happen? Is this an OS dependent thing?
#include "stdio.h"
const int SIZE = 12;
int _tmain(int argc, _TCHAR * argv[]) {
unsigned char c[SIZE] = {
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
};
unsigned int * ptr = (unsigned int * ) c;
int i;
printf("Int size=%d\n", sizeof(unsigned long));
for (i = 0; i < sizeof(c); i++) {
printf("%X, ", c[i]);
}
printf("\n\n");
for (i = 0; i < sizeof(c) / sizeof(unsigned long); i++) { * ptr++ = i;
}
for (i = 0; i < sizeof(c); i++) {
printf("%X, ", c[i]);
}
printf("\n");
return 0;
}
Here is the output:
Int size=4
1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C,
0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0,
Your architecture is Little Endian, which means the least significant byte is stored first in memory:
In your case 0x00000001 is written in the order [0x01, 0x00, 0x00, 0x00].
This is caused by endianness of your CPU architecture. Your architecture seems to be little endian to cause this kind of inversions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With