4x8 位整数转 32 位整数
我
_int8 arr[0] = 0;
_int8 arr[1] = 0;
_int8 arr[2] = 14;
_int8 arr[3] = 16;
需要使用 arr[0] 作为第一部分将其转换为 _int32 <..>最后是 arr[3]。 最后应该是
_int32 back = 3600;
我应该使用位移位或类似的东西来实现这一点吗?
I have
_int8 arr[0] = 0;
_int8 arr[1] = 0;
_int8 arr[2] = 14;
_int8 arr[3] = 16;
I need to convert it to one _int32 using as arr[0] as first part <..> and arr[3] as last.
In the end it should be
_int32 back = 3600;
Should I use bit shifts or smth like that to achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将它们全部转换为
int
然后使用:或者:
Cast them all to
int
then use:Alternatively:
如果您知道字节顺序(即大端或小端,请在维基百科上查看),并且数组以正确的顺序设置,您可以这样做:
这只会将您的 4 字节数组解释为保存单个 32 位整数。不过,在您的示例中,我认为您已经将其设置为大端,而 x86 则没有。所以你需要交换一些字节。
例如:
或者类似的东西。
If you know the byte ordering (i.e. big endian or little endian, check it out on wikipedia), and the array is set up in the right order you can just do:
That'll just interpret your array of 4 bytes as a buffer holding a single 32-bit integer. In your example though, I think you've got it set up for big endian and x86 isn't. So you'd need to swap some bytes.
For instance:
or something like that.
这可能是我的 SCO 编译器,但我认为如果我不使用 (arr[0]&0xff) 等进行转换,我就会遇到问题。当然不会伤害任何东西。
It's probably my SCO compiler but I think I've had problems if I didn't use (arr[0]&0xff) and so forth for doing the shifts. Certainly doesn't hurt anything.