简体   繁体   English

从二进制文件中将 unsigned int 读入 uint64_t

[英]Reading unsigned int into uint64_t from binary file

I am trying to read a binary file using fstream.我正在尝试使用 fstream 读取二进制文件。 I know the types of everything in this file but there are two different versions, an old and a new version.我知道这个文件中所有内容的类型,但有两个不同的版本,一个旧版本和一个新版本。 The old version contains variables of type 'unsigned int' deemed to have insufficient range, and are replaced by 'uint64_t' in the new version.旧版本包含被认为范围不足的“unsigned int”类型的变量,并在新版本中被“uint64_t”取代。 I'd like one file reader capable of reading both formats(for backwards compatibility).我想要一个能够读取两种格式的文件阅读器(为了向后兼容)。 The read result should always be a uint64_t.读取结果应始终为 uint64_t。

I am sure this is a common problem.我相信这是一个常见问题。 I've tried simply reading 4 bytes from an ifstream into the memory of the uint64_t, comparable to the snippet below(without checking for any problems):我试过简单地从 ifstream 读取 4 个字节到 uint64_t 的 memory 中,与下面的代码片段相当(没有检查任何问题):

std::uint64_t buff=0;
std::ifstream is(filePath, std::ios_base::binary)
std::is.read(&buff,sizeof(unsigned int));

This gives me the correct value but I realize this might be subject to endianness.这给了我正确的价值,但我意识到这可能会受到字节顺序的影响。 Is there a common method to solve this problem?有解决这个问题的通用方法吗?

You need to read it into a variable of the correct type and then you can assign it to your uint64_t variable.您需要将它读入正确类型的变量,然后您可以将它分配给您的uint64_t变量。

static_assert(std::endian::native == std::endian::big ||
              std::endian::native == std::endian::little);
                
constexpr auto file_endianess = std::endian::big; // or little

std::uint64_t buff = 0;
std::ifstream is(filePath, std::ios_base::binary);
if (is) {
    std::uint32_t temp;
    if (is.read(reinterpret_cast<char*>(&temp), sizeof temp)) {
        
        // ... deal with endianess here ...
        // (example from C++23 below)
        #ifdef __cpp_lib_byteswap
        if constexpr(std::endian::native != file_endianess) {
            temp = std::byteswap(temp);
        }
        #else
        // an alternative endianess solution goes here
        #endif

        buff = temp;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM