Search code examples
c++long-integerifstreamendianness

Reversing long read from file?


I'm trying to read a long (signed, 4 bytes) from a binary file in C++. My main concerns are: portability (longs are different sizes on different platforms), when you read from binary files w/ std::ifstream, it reverses the byte order (to my machine's endianness).

I understand for data types like unsigned int, you can simply use bitwise operators and shift and AND each byte to reverse the byte order after being read from a file.

I'm just not sure what I'd do for this: Currently my code will give a nonsense value:

long value;
in.seekg(0x3c);
in.read(reinterpret_cast<char*>(&value), sizeof(long));

I'm not sure how I can achieve portability (I read something about unions and char*) and also reverse the signed long it reads in.

Thanks.


Solution

  • Rather than using long, use int32_t from <stdint.h> to directly specify a 32-bit integer. (or uint32_t for unsigned).

    Use htonl and ntohl as appropriate to get to/from network byte order.

    Better:

    int32_t value;
    in.seekg(0x3c);
    in.read(reinterpret_cast<char*>(&value), sizeof(value));
    value = ntohl(value); // convert from big endian to native endian