From 8d43ddf9b09fbc0318da1c3b49a559fb47b9750b Mon Sep 17 00:00:00 2001 From: Ladislas de Toldi Date: Mon, 30 May 2022 14:50:57 +0200 Subject: [PATCH] :sparkles: (MemoryUtils): Add combineBytes function --- libs/Utils/include/MemoryUtils.h | 16 ++++++++++++++++ libs/Utils/tests/MemoryUtils_test.cpp | 16 ++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/libs/Utils/include/MemoryUtils.h b/libs/Utils/include/MemoryUtils.h index cf3c054f8f..fc1b0ffbb8 100644 --- a/libs/Utils/include/MemoryUtils.h +++ b/libs/Utils/include/MemoryUtils.h @@ -18,4 +18,20 @@ constexpr auto getHighByte(uint16_t value) noexcept -> uint8_t return static_cast(value >> 8); } +struct TwoBytes { + uint8_t high {}; + uint8_t low {}; +}; + +constexpr auto combineBytes(TwoBytes bytes) noexcept -> uint16_t +{ + auto both = uint16_t {}; + + both = bytes.high; + both = static_cast(both << 8); + both |= bytes.low; + + return both; +} + } // namespace leka::utils::memory diff --git a/libs/Utils/tests/MemoryUtils_test.cpp b/libs/Utils/tests/MemoryUtils_test.cpp index 1e95af6cc4..2c231a1120 100644 --- a/libs/Utils/tests/MemoryUtils_test.cpp +++ b/libs/Utils/tests/MemoryUtils_test.cpp @@ -98,3 +98,19 @@ TEST(MemoryUtilsTest, getHighByte) ASSERT_EQ(0b1111'1111, high); } + +TEST(MemoryUtilsTest, combineTwoBytes) +{ + auto high = uint8_t {0xAB}; + auto low = uint8_t {0xCD}; + + auto both = combineBytes({.high = high, .low = low}); + + EXPECT_EQ(both, 0xABCD); + + auto new_high = getHighByte(both); + auto new_low = getLowByte(both); + + EXPECT_EQ(new_high, high); + EXPECT_EQ(new_low, low); +}