当我注意到它的输出完全错误时,我正在测试一个简单的编译器.实际上,输出的字节顺序从小到大都是交换的.仔细检查后,违规代码就是这样的:
const char *bp = reinterpret_cast<const char*>(&command._instruction);
for (int i = 0; i < 4; ++i)
out << bp[i];
Run Code Online (Sandbox Code Playgroud)
一个四字节的指令被重新解释为一组单字节字符并打印到stdout(它很笨重,是的,但那个决定不是我的).对于我来说,为什么这些位将被交换似乎不合乎逻辑,因为char指针应该首先指向最重要的位(在此x86系统上).例如,给定0x00 ... 04,char指针应指向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 << …Run Code Online (Sandbox Code Playgroud)