gpt4 book ai didi

c++ - reinterpret_cast 交换位?

转载 作者:行者123 更新时间:2023-11-30 00:49:26 26 4
gpt4 key购买 nike

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

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

四字节指令被重新解释为一组单字节字符并打印到标准输出(这很笨拙,是的,但那个决定不是我的)。为什么要交换这些位对我来说似乎不合逻辑,因为 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 << std::bitset<32>(foo) << std::endl;

return 0;
}

输出:

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

最佳答案

It doesn't seem logical to me why the bits would be swapped, since the char pointer should be pointing to the most-significant (on this x86 system) bits at first.

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

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

关于c++ - reinterpret_cast 交换位?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28145361/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com