c 位操作(字节顺序)

问题描述 投票:0回答:2

有人可以向我解释这段代码吗?我从汇编器那里收到了一些字节码,现在我必须在我的虚拟机中使用它。使用此代码,但我不知道它是如何工作的以及它的用途。

static int32_t bytecode_to_int32 (const uint8_t* bytes)
{
  uint32_t result = (uint32_t)bytes[0] << 24 |
                    (uint32_t)bytes[1] << 16 |
                    (uint32_t)bytes[2] <<  8 |
                    (uint32_t)bytes[3] <<  0 ;
  return (int32_t)result;
}
c bit-manipulation bit endianness
2个回答
2
投票

它由 4 个字节组成一个 32 位的字。 例如,如果字节是:第一个:0x12,第二个:0x34,第三个:0x56,第四个:0x78 然后:

static int32_t bytecode_to_int32 (const uint8_t* bytes)
{
  uint32_t result = (uint32_t)bytes[0] << 24 | // -> 0x12000000
                    (uint32_t)bytes[1] << 16 | // -> 0x00340000
                    (uint32_t)bytes[2] <<  8 | // -> 0x00005600
                    (uint32_t)bytes[3] <<  0 ; // -> 0x00000078
  return (int32_t)result; // bitwise oring this result -> 0x12345678
}

0
投票

此函数尝试将

uint8_t[4]
中的四个字节组合成一个具有大端字节顺序的
uint32_t
,将结果转换为带符号的
int32_t
,并返回它。

所以,如果您将指向数组

{ 0xAA, 0xBB, 0xCC, 0xDD }
的指针传递给函数,它会将它们组合成一个 32 位整数,该整数的最高有效字节来自数组中的最低地址,从而为您提供
0xAABBCCDD
-1430532899
.

但是,如果参数

bytes
指向的数组长度不是至少四个字节,则它具有未定义的行为。

© www.soinside.com 2019 - 2024. All rights reserved.