reinterpret_cast swaps bits?

reinterpret_cast swaps bits?

本文关键字:bits swaps cast reinterpret      更新时间:2023-10-16

当我注意到它的输出完全错误时,我正在测试一个简单的编译器。事实上,输出的字节序从小到大交换。经过仔细检查,违规代码竟然是这样的:

const char *bp = reinterpret_cast<const char*>(&command._instruction);
for (int i = 0; i < 4; ++i)
  out << bp[i];

四字节指令被重新解释为一组单字节字符并打印到 stdout(是的,这很笨重,但这个决定不是我的)。对我来说,为什么要交换位似乎不合逻辑,因为 char 指针首先应该指向最重要的(在这个 x86 系统上)位。例如,给定0x00...04,字符指针应指向0x00,而不是0x04。情况是后者。

我创建了一个简单的代码演示:

法典

#include <bitset>
#include <iostream>
#include <stdint.h>
int main()
{
  int32_t foo = 4;
  int8_t* cursor = reinterpret_cast<int8_t*>(&foo);
  std::cout << "Using a moving 8-bit pointer:" << std::endl;
  for (int i = 0; i < 4; ++i)
    std::cout << std::bitset<8>(cursor[i]) << " "; // <-- why?
  std::cout << std::endl << "Using original 4-byte int:" << std::endl;
  std::cout << std::bitset<32>(foo) << std::endl;
  return 0;
}

输出:

Using a moving 8-bit pointer:
00000100 00000000 00000000 00000000
Using original 4-byte int:
00000000000000000000000000000100

对我来说,为什么要交换位似乎不合逻辑,因为 char 指针首先应该指向最重要的(在这个 x86 系统上)位。

在 x86 系统上,指向多字节对象基的指针不指向最高有效字节,而是指向最低有效字节。这称为"小字节序"字节序。

在 C 中,如果我们获取一个占用多个字节的对象的地址,并将其转换为 char * ,它指向对象的基数:被认为是最低有效地址的那个,指针可以从中正位移(用 +++ 等)到达其他字节。