简体   繁体   中英

Reading an uint32_t from a byte stream

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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