From 905e8dd17fbaec6abeb1457d0379062a5c97c487 Mon Sep 17 00:00:00 2001 From: Eric Jiang <321497+erjiang@users.noreply.github.com> Date: Sat, 14 Jun 2025 09:02:01 -0700 Subject: [PATCH] Fix endian conversion when reading weight --- usbscale.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/usbscale.c b/usbscale.c index 563a187..e4a8c2f 100644 --- a/usbscale.c +++ b/usbscale.c @@ -376,8 +376,10 @@ static int print_scale_data(unsigned char* dat) { uint8_t unit = dat[2]; // According to the docs, scaling applied to the data as a base ten exponent int8_t expt = dat[3]; - // convert to machine order at all times - double weight = (double) le16toh(dat[5] << 8 | dat[4]); + // combine the little-endian weight bytes without relying on system + // endianness. dat[4] is the low byte and dat[5] is the high byte. + uint16_t raw_weight = (uint16_t)dat[4] | ((uint16_t)dat[5] << 8); + double weight = (double)raw_weight; // since the expt is signed, we do not need no trickery weight = weight * pow(10, expt);