4x8 位整数转 32 位整数

发布于 2024-10-12 06:45:29 字数 252 浏览 2 评论 0原文

_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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

む无字情书 2024-10-19 06:45:29

将它们全部转换为 int 然后使用:

(arr[0] << 24) | (arr[1] << 16) | (arr[2] << 8) | arr[3]

或者:

_int32 back = 0;
for (int i = 0; i < 4; ++i)
    back = (back << 8) | arr[i];

Cast them all to int then use:

(arr[0] << 24) | (arr[1] << 16) | (arr[2] << 8) | arr[3]

Alternatively:

_int32 back = 0;
for (int i = 0; i < 4; ++i)
    back = (back << 8) | arr[i];
对你而言 2024-10-19 06:45:29

如果您知道字节顺序(即大端或小端,请在维基百科上查看),并且数组以正确的顺序设置,您可以这样做:

back = *(_int32 *)arr;

这只会将您的 4 字节数组解释为保存单个 32 位整数。不过,在您的示例中,我认为您已经将其设置为大端,而 x86 则没有。所以你需要交换一些字节。

例如:

_int32 back = arr[0] << 24 | arr[1] << 16 | arr[2] << 8 | arr[3];

或者类似的东西。

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:

back = *(_int32 *)arr;

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:

_int32 back = arr[0] << 24 | arr[1] << 16 | arr[2] << 8 | arr[3];

or something like that.

守望孤独 2024-10-19 06:45:29

这可能是我的 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文