1

I'm reading bytes from a PNG image via std::basic_ifstream<std::uint8_t>. I'm having problems reading a sequence of 4 bytes that should be interpreted as 32 bit int.

std::uint32_t read_chunk_length(std::basic_ifstream<std::uint8_t> &ifs) {
    std::uint32_t length;
    ifs.read(reinterpret_cast<std::uint8_t*>(&length), 4);
    return length;
}

When reading a sequence that is 00 00 00 0d and should thus be 0xd (or 13), the above function gives me 0xd000000 (or 218103808 instead). Apologies if the question is trivial.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
A.B.
  • 15,364
  • 3
  • 61
  • 64

1 Answers1

2

This is a byte ordering issue - the stream on disk contains the bytes in the opposite order (big endian as specified in the PNG spec) than your architecture mandates for integers (likely little-endian). You have to manually reverse the order of bytes to solve this.

Alexander Gessler
  • 45,603
  • 7
  • 82
  • 122