问题描述
我通过 std :: basic_ifstream< std :: uint8_t>
从PNG图像读取字节。我在读取一个4字节的序列时出现问题,应该解释为32位int。
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;
}
当读取序列为00 00 00 0d时,应为0xd或13),上面的函数给我0xd000000(或218103808)。
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.
这篇关于从字节流读取uint32_t的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!