From 28c4ad34d726cce382e93fccecda1fa4edc7ea8f Mon Sep 17 00:00:00 2001
From: Simon McVittie <[EMAIL REDACTED]>
Date: Wed, 25 May 2022 14:06:27 +0100
Subject: [PATCH] tiny_jpeg: Don't byteswap 16-bit words if already big-endian
Previously, this assumed that native endianness was always little-endian,
which is true for x86 and most other architectures, but untrue for
some (mostly older) unusual architectures.
Forwarded: https://github.com/serge-rgb/TinyJPEG/pull/16
Signed-off-by: Simon McVittie <smcv@collabora.com>
---
tiny_jpeg.h | 15 ++++++++++-----
1 file changed, 10 insertions(+), 5 deletions(-)
diff --git a/tiny_jpeg.h b/tiny_jpeg.h
index e6023d0d..c64bbe5b 100644
--- a/tiny_jpeg.h
+++ b/tiny_jpeg.h
@@ -385,12 +385,17 @@ static const uint8_t tjei_zig_zag[64] =
35, 36, 48, 49, 57, 58, 62, 63,
};
-// Memory order as big endian. 0xhilo -> 0xlohi which looks as 0xhilo in memory.
-static uint16_t tjei_be_word(const uint16_t le_word)
+// Memory order as big endian.
+// On little-endian machines: 0xhilo -> 0xlohi which looks as 0xhi 0xlo in memory
+// On big-endian machines: leave 0xhilo unchanged
+static uint16_t tjei_be_word(const uint16_t native_word)
{
- uint16_t lo = (le_word & 0x00ff);
- uint16_t hi = ((le_word & 0xff00) >> 8);
- return (uint16_t)((lo << 8) | hi);
+ uint8_t bytes[2];
+ uint16_t result;
+ bytes[1] = (native_word & 0x00ff);
+ bytes[0] = ((native_word & 0xff00) >> 8);
+ memcpy(&result, bytes, sizeof(bytes));
+ return result;
}
// ============================================================