Luca Marconato Luca Marconato - 1 year ago 57
C++ Question

Read a file written in bigendian

My machine works in little endian.
I have to read using C++ std::ios::binary some files with big endian encoding. Is there any standard and fast way for doing it?
For the moment, after having read raw data I do the following:

(reading a double)

char raw [8];
double d = 0; //maybe initialization is not needed,8); //4 for an int
for(int k = 0; k < 8; k++) {
memcpy((void *)(((char *)(&d))+k), (const void *)(raw+j+7-k), 1);

(reading an integer)

char raw [4];,4); //4 for an int
int i = (raw[j] << 24) | (raw[j+1] << 16) | (raw[j+2] << 8) | raw[j+3];

Answer Source

Use the htonl and ntohl ('host to network long" and "network to host long") functions to convert between host and network byte order. Network byte order is big endian, and on your architecture host byte order is little endian.

You should also always use explicitly-sized unsigned integer types when doing this kind of bit-mangling, not int. You can reinterpret_cast to the desired type of the data later, e.g. start with uint64_t to read in a double.

uint32_t little_endian_thing;
uint32_t big_endian_thing;, sizeof(uint32_t));
little_endian_thing = ntohl(big_endian_thing);