一个char占用1字节,一个int占用4个字节。我想将char[4]中的每个字节逐字节复制到int中。我考虑了不同的方法,但得到了不同的答案。
char str[4]="abc";
unsigned int a = *(unsigned int*)str;
unsigned int b = str[0]<<24 | str[1]<<16 | str[2]<<8 | str[3];
unsigned int c;
memcpy(&c, str, 4);
printf("%u %u %u\n", a, b, c);
输出结果为6513249 1633837824 6513249。
哪一个是正确的?出了什么问题?
printf("%08X %08X %08X\n", a, b, c);
,注意相同的字节都在,但顺序不同。 - chux - Reinstate Monica