From 76690e69007d2aff3488e7faa95f23b3726d600e Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Sat, 28 Feb 2026 08:48:18 -1000 Subject: [PATCH] [ld2410/ld2412] Fix two_byte_to_int using signed char causing incorrect values The two_byte_to_int() function used `char` parameters instead of `uint8_t`, causing sign extension for byte values >= 0x80. This produced incorrect sensor values for distances where value % 256 >= 128 (e.g. 128cm reported as -128, 200cm reported as -56). Also removed the unnecessary `(int16_t)` cast and switched from `+` to `|` for proper bitwise assembly. Co-Authored-By: Claude Opus 4.6 --- esphome/components/ld2410/ld2410.cpp | 2 +- esphome/components/ld2412/ld2412.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/esphome/components/ld2410/ld2410.cpp b/esphome/components/ld2410/ld2410.cpp index dd1d53857d0..631b99d4b25 100644 --- a/esphome/components/ld2410/ld2410.cpp +++ b/esphome/components/ld2410/ld2410.cpp @@ -173,7 +173,7 @@ static constexpr uint8_t DATA_FRAME_FOOTER[HEADER_FOOTER_SIZE] = {0xF8, 0xF7, 0x // MAC address the module uses when Bluetooth is disabled static constexpr uint8_t NO_MAC[] = {0x08, 0x05, 0x04, 0x03, 0x02, 0x01}; -static inline int two_byte_to_int(char firstbyte, char secondbyte) { return (int16_t) (secondbyte << 8) + firstbyte; } +static inline int two_byte_to_int(uint8_t firstbyte, uint8_t secondbyte) { return (secondbyte << 8) | firstbyte; } static inline bool validate_header_footer(const uint8_t *header_footer, const uint8_t *buffer) { return std::memcmp(header_footer, buffer, HEADER_FOOTER_SIZE) == 0; diff --git a/esphome/components/ld2412/ld2412.cpp b/esphome/components/ld2412/ld2412.cpp index 484d5bd281c..e97dfb86309 100644 --- a/esphome/components/ld2412/ld2412.cpp +++ b/esphome/components/ld2412/ld2412.cpp @@ -192,7 +192,7 @@ static constexpr uint8_t DATA_FRAME_FOOTER[HEADER_FOOTER_SIZE] = {0xF8, 0xF7, 0x // MAC address the module uses when Bluetooth is disabled static constexpr uint8_t NO_MAC[] = {0x08, 0x05, 0x04, 0x03, 0x02, 0x01}; -static inline int two_byte_to_int(char firstbyte, char secondbyte) { return (int16_t) (secondbyte << 8) + firstbyte; } +static inline int two_byte_to_int(uint8_t firstbyte, uint8_t secondbyte) { return (secondbyte << 8) | firstbyte; } static inline bool validate_header_footer(const uint8_t *header_footer, const uint8_t *buffer) { return std::memcmp(header_footer, buffer, HEADER_FOOTER_SIZE) == 0;