从文件中反转长时间读取?
Reversing long read from file?
我正在尝试从 C++ 中的二进制文件中读取一个 long(有符号,4 字节)。
我主要关心的是:可移植性(longs 在不同平台上的大小不同),当你从带有 std::ifstream 的二进制文件中读取时,它会颠倒字节顺序(到我机器的字节顺序)。
我了解对于像 unsigned int 这样的数据类型,您可以简单地使用按位运算符和 shift 和 AND 来反转每个字节从文件中读取后的字节顺序。
我只是不确定我会为此做什么:
目前我的代码会给出一个无意义的值:
long value;
in.seekg(0x3c);
in.read(reinterpret_cast<char*>(&value), sizeof(long));
我不确定如何实现可移植性(我阅读了一些关于 union 和 char* 的内容)以及反转它读入的带符号的 long。
谢谢。
我建议您使用 htonl、htnons、ntohl 和 ntohs 等函数。这些在网络编程中用于实现相同的目标:可移植性和字节顺序的独立性。
由于跨平台支持对您很重要,我建议您使用 cstdint 来指定类型的大小。你将能够说 int32_t x
(例如)并且知道你正在获取 32 位数据。
关于数据的字节顺序,我建议对一种格式进行标准化(例如,所有数据都以小端格式编写)并将您的 I/O 操作包装在 class 中并使用它来read/write 数据。然后用一个#define
来决定如何读取数据:
#ifdef BIG_ENDIAN
// Read the data that is in little endian format and convert
#else
// We're in little endian mode so no need to convert data
#endif
或者,您可以考虑使用 Google Protobuf 之类的东西,它会为您解决所有编码问题。
不使用 long
,而是使用 <stdint.h>
中的 int32_t
直接指定一个 32 位整数。 (或 uint32_t
无符号)。
酌情使用htonl and ntohl获得to/from网络字节顺序。
更好:
int32_t value;
in.seekg(0x3c);
in.read(reinterpret_cast<char*>(&value), sizeof(value));
value = ntohl(value); // convert from big endian to native endian
我正在尝试从 C++ 中的二进制文件中读取一个 long(有符号,4 字节)。 我主要关心的是:可移植性(longs 在不同平台上的大小不同),当你从带有 std::ifstream 的二进制文件中读取时,它会颠倒字节顺序(到我机器的字节顺序)。
我了解对于像 unsigned int 这样的数据类型,您可以简单地使用按位运算符和 shift 和 AND 来反转每个字节从文件中读取后的字节顺序。
我只是不确定我会为此做什么: 目前我的代码会给出一个无意义的值:
long value;
in.seekg(0x3c);
in.read(reinterpret_cast<char*>(&value), sizeof(long));
我不确定如何实现可移植性(我阅读了一些关于 union 和 char* 的内容)以及反转它读入的带符号的 long。
谢谢。
我建议您使用 htonl、htnons、ntohl 和 ntohs 等函数。这些在网络编程中用于实现相同的目标:可移植性和字节顺序的独立性。
由于跨平台支持对您很重要,我建议您使用 cstdint 来指定类型的大小。你将能够说 int32_t x
(例如)并且知道你正在获取 32 位数据。
关于数据的字节顺序,我建议对一种格式进行标准化(例如,所有数据都以小端格式编写)并将您的 I/O 操作包装在 class 中并使用它来read/write 数据。然后用一个#define
来决定如何读取数据:
#ifdef BIG_ENDIAN
// Read the data that is in little endian format and convert
#else
// We're in little endian mode so no need to convert data
#endif
或者,您可以考虑使用 Google Protobuf 之类的东西,它会为您解决所有编码问题。
不使用 long
,而是使用 <stdint.h>
中的 int32_t
直接指定一个 32 位整数。 (或 uint32_t
无符号)。
酌情使用htonl and ntohl获得to/from网络字节顺序。
更好:
int32_t value;
in.seekg(0x3c);
in.read(reinterpret_cast<char*>(&value), sizeof(value));
value = ntohl(value); // convert from big endian to native endian