简体   繁体   English

将二进制文件读取到整数数组

[英]Reading binary file to integer array

I am trying to read a binary file into an array of unsigned 32-bit integers. 我正在尝试将二进制文件读入无符号32位整数数组。 However, I am experiencing some problems with endianness, as my input is reversed in groups of 8 bits (eg 0x65206669 becoming 0x69662065 ). 但是,我遇到了字节序问题,因为我的输入以8位为一组反转(例如0x65206669变为0x69662065 )。 This is how I read the file: 这是我读取文件的方式:

std::ifstream input;
input.open(filename.c_str(), std::ios::in | std::ios::binary);
if (!input.is_open()) return false;

uint32_t buffer[262144];
input.read((char*)buffer, 1048576);

Do I need to convert the buffer's endian, or is there some function which can read a binary file into integers? 我需要转换缓冲区的字节序,还是有一些函数可以将二进制文件读取为整数?

Binary files represent multibyte types, such as 32-bit int s in a way that is often specific to the architecture on which they were generated. 二进制文件以通常特定于其生成体系结构的方式表示多字节类型,例如32位int Although reading int s from a binary file will produce the same numbers as were written to the file on the same machine, reading files produced by other machines may give you incorrect results. 尽管从二进制文件读取int会产生与在同一台计算机上写入文件相同的数字,但是读取其他计算机产生的文件可能会给您带来不正确的结果。

It looks like the file that you are reading has been produced on a computer with the opposite endianness. 您正在读取的文件似乎是在具有相反字节序的计算机上生成的。 If you plan to read these files only on your computer, you could write a simple function that swaps the byte order for you. 如果打算仅在计算机上读取这些文件,则可以编写一个简单的函数来为您交换字节顺序。 If you plan to make binary files that are independent of architecture, you should pick one byte order (for example, the network order, also known as "big-endian") and then use byte reordering routines specific to your system . 如果计划制作独立于体系结构的二进制文件,则应选择一个字节顺序(例如,网络顺序,也称为“ big-endian”),然后使用特定于系统的字节重新排序例程

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

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