From cf654441bef096beb9d2d291355a46d211ff8186 Mon Sep 17 00:00:00 2001 From: Bob Polis Date: Sun, 14 Nov 2021 14:22:00 +0100 Subject: [PATCH] fixed 24-bit reading and writing --- byte_order_stuff.cpp | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/byte_order_stuff.cpp b/byte_order_stuff.cpp index acc13d0..1c67247 100644 --- a/byte_order_stuff.cpp +++ b/byte_order_stuff.cpp @@ -31,11 +31,12 @@ std::string data_streamer::get4chars(std::istream& file) const { uint32_t data_streamer::getui24(std::istream& file) const { char buf[4] = {0}; - file.read(&buf[1], 3); + int i = cur_byte_order() == byte_order::little_endian ? 0 : 1; + file.read(&buf[i], 3); if (cur_byte_order() != _target_byte_order) { - char tmp = buf[1]; - buf[1] = buf[3]; - buf[3] = tmp; + char tmp = buf[i]; + buf[i] = buf[i + 2]; + buf[i + 2] = tmp; } return *reinterpret_cast(buf); } @@ -62,12 +63,13 @@ void data_streamer::put4chars(const std::string& s, std::ostream& file) const { void data_streamer::putui24(uint32_t val, std::ostream& file) const { char* buf = reinterpret_cast(&val); + int i = cur_byte_order() == byte_order::little_endian ? 0 : 1; if (cur_byte_order() != _target_byte_order) { - char tmp = buf[1]; - buf[1] = buf[3]; - buf[3] = tmp; + char tmp = buf[i]; + buf[i] = buf[i + 2]; + buf[i + 2] = tmp; } - file.write(&buf[1], 3); + file.write(&buf[i], 3); } void data_streamer::putsi24(int32_t val, std::ostream& file) const {