繁体   English   中英

c 位操作(字节序)

[英]c bit manipulation (endianess)

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

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;
}

它由 4 个字节构成一个 32 位的字。 例如,如果字节是: 1st: 0x12 , 2nd: 0x34, 3rd: 0x56, 4th: 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
}

此函数尝试将uint8_t[4]的四个字节组合成一个具有大端字节序的uint32_t ,将结果转换为有符号的int32_t ,然后返回。

因此,如果您将指向数组{ 0xAA, 0xBB, 0xCC, 0xDD }的指针传递给函数,它会将它们组合成一个 32 位整数,整数的最高有效字节来自数组中的最低地址,给你0xAABBCCDD-1430532899

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM