Question

I am trying to read a binary file into an array of unsigned 32-bit integers. However, I am experiencing some problems with endianness, as my input is reversed in groups of 8 bits (e.g. 0x65206669 becoming 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?

Was it helpful?

Solution

Binary files represent multibyte types, such as 32-bit ints in a way that is often specific to the architecture on which they were generated. Although reading ints 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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top