c++ - 二进制读取、reinterpret_cast 和字节顺序

标签 c++ binaryfiles endianness reinterpret-cast

我目前正在处理字节顺序相关的问题。

假设我在大端系统中有一个大端文件。

此文件中的第一个值是 2882400152 = 0xABCDEF98,它是一个整数 4。

要读取整数 4 中的值,_myint4,我只需这样做:

mystream.read(reinterpret_cast<char*>(&_myint4), sizeof(_myint4))

问题是:读取文件中的整数 4 值,在整数 8 中,_myint8 等价于什么?

  • 对于大端文件和系统?
  • 用于小端文件和系统?

我的第一个猜测是这样的:

mystream.read((reinterpret_cast<char*>(&_myint8))+4, 4); // big-endian file/system
mystream.read(reinterpret_cast<char*>(&_myint8), 4); // little-endian file/system

但我一点也不确定。执行此操作的好方法是什么?

重要提示:我不能使用临时整数 4 值,我需要直接读取 _myint8 中的整数 4。

最佳答案

你的猜测似乎是正确的:

_myint8 = 0;
mystream.read((reinterpret_cast<char*>(&_myint8))+4, 4); // big-endian file/system
mystream.read(reinterpret_cast<char*>(&_myint8), 4); // little-endian file/system

要自己弄清楚字节顺序,玩一下 Python 可能会有所帮助:

>>> import struct
>>> struct.pack(">Q", 0xabcdef98)    // Big-endian 8-byte int.
'\x00\x00\x00\x00\xab\xcd\xef\x98'   // Its layout in memory.
>>> struct.pack(">I", 0xabcdef98)    // Big-endian 4-byte int.
'\xab\xcd\xef\x98'

>>> struct.pack("<Q", 0xabcdef98)    // Little-endian 8-byte int.
'\x98\xef\xcd\xab\x00\x00\x00\x00'
>>> struct.pack("<I", 0xabcdef98)    // Little-endian 4-byte int.
'\x98\xef\xcd\xab'

所以你是对的,你只需要确保你在内存中没有覆盖的地方有零。

关于c++ - 二进制读取、reinterpret_cast 和字节顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12648834/

相关文章:

c++ - 将纬度/经度转换为 X/Y 坐标

c# - 以正确的方式从二进制文件中提取存储的 png 图像

ios - NSArray 和字节顺序

C++ 编译器无法从迭代器派生出正确的类型

c++ - 将文本从子 GUI 进程发送到控制台父进程的最简单方法是什么?

c++ - QTCPSocket同时由定时器启动

c++ - char* 是否用作内存中字节的位置?

language-agnostic - 在可执行程序的上下文中, "binaries"和 "executables"之间的区别在哪里?

c++ - 负序转换为负数?

我可以创建适用于不同字节序的颜色结构吗?