转换4个字节CHAR在C INT32 [英] Convert 4 bytes char to int32 in C
本文介绍了转换4个字节CHAR在C INT32的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我先转换成一个Int32数为char [4]数组,然后通过为(int *)数组转换回INT32,但数量并不像以前一样:
I first convert an int32 number to char[4] array, then convert the array back to int32 by (int *), but the number isn't the same as before:
unsigned int num = 2130706432;
unsigned int x;
unsigned char a[4];
a[0] = (num>>24) & 0xFF;
a[1] = (num>>16) & 0xFF;
a[2] = (num>>8) & 0xFF;
a[3] = num & 0xFF;
x = *(int *)a;
printf("%d\n", x);
输出为127。如果我设置NUM = 127,输出为2130706432。
没有任何人有想法?
the output is 127. And if I set num = 127, the output is 2130706432. Does anyone have ideas?
推荐答案
反向顺序的一个[]索引,例如,。一个[0] - >一个[3]
Reverse the order of the a[] indexes, e.g,. a[0] -> a[3]
我觉得你有相反的字节顺序。
I think you have the endianness in reverse.
试试这个:
a[3] = (num>>24) & 0xFF;
a[2] = (num>>16) & 0xFF;
a[1] = (num>>8) & 0xFF;
a[0] = num & 0xFF;
这篇关于转换4个字节CHAR在C INT32的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文