reinterpret_cast swaps bits?
reinterpret_cast swaps bits?
当我注意到它的输出完全错误时,我正在测试一个简单的编译器。事实上,输出的字节序从小到大交换。经过仔细检查,违规代码竟然是这样的:
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 *
,它指向对象的基数:被认为是最低有效地址的那个,指针可以从中正位移(用 +
或 ++
等)到达其他字节。
相关文章:
- 我在 #include < bits/stdc++h.> 放置时出错"No such file or directory"
- bits/stdc++.h 包含哪些头文件?
- Arduino Uno - serial.read to a struct of bits
- 为什么这两个代码给出不同的输出?// bits.c float_i2f
- 当索引为 1 时,_BitScanReverse返回 0,这意味着根据 MS "no set bits were found"
- Android CMake "致命错误: 'bits/libc-header-start.h' 文件未找到"
- 由mpglib输出的"hip: Can't rewind stream by 74 bits"到底意味着什么?
- 用rvalue参考和变异模板bits bits bys blamda by
- "cannot open source file bits/stdc++.h"在Visual Studio中
- concatenate bits C++
- 使用 <bits/stdc++.h> 给出全局变量的歧义
- 作为抽象,C++是否支持表示两个以上值之一的"bits"?
- reinterpret_cast swaps bits?
- 为什么可以在没有返回类型的情况下运行 /usr/include/c ++/5/bits/fstream.tcc 中
- 无法打开源文件"bits/c++config.h" icpc 错误
- VirtualTreeView - Embarcadero C++ Builder XE7 - 64 bits
- 可以在 GCC "bits/g++config.h"中编辑定义吗?
- G++ 4.6 问题没有标头 cstring 所需的 <bits/c++config.h> 文件
- C++随机生成器 mt19937 中,它是在<random>还是<bits/random.h>?
- Boost::multiprecision::export_bits在导出cpp_int类型为bits时丢失符号