我创建了一些简单的代码来测试将char数组转换为int指针.这正如我预期的那样工作正常,但是当我使用指针写入数组时,当我打印出c数组时,数据交换了MSB< - > LSB.为什么会这样?这是操作系统依赖的吗?
#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; }
这是输出:
Int size=4 1,A,B,C,1,
解决方法
您的体系结构是Little Endian,这意味着最低有效字节首先存储在内存中:
在您的情况下,0x00000001按[0x01,0x00,0x00]的顺序写入.