Compare commits

...
2 changed files with 30 additions and 0 deletions

No files matched your search

+10
View File
@@ -1155,6 +1155,16 @@ bool random_bytes(uint8_t *data, size_t len);
/// @name Bit manipulation
///@{
/// The high 4 bits of a byte, e.g. high_nibble(0xA5) == 0xA.
constexpr uint8_t high_nibble(uint8_t byte) { return byte >> 4; }
/// The low 4 bits of a byte, e.g. low_nibble(0xA5) == 0x5.
constexpr uint8_t low_nibble(uint8_t byte) { return byte & 0x0F; }
/// Encode a 12-bit value from its high 8 and low 4 bits, e.g. encode_uint12(0x12, 0x3) == 0x123.
/// Bits above the low 4 of \p low_bits are ignored.
constexpr uint16_t encode_uint12(uint8_t high_bits, uint8_t low_bits) {
return (static_cast<uint16_t>(high_bits) << 4) | low_nibble(low_bits);
}
/// Encode a 16-bit value given the most and least significant byte.
constexpr uint16_t encode_uint16(uint8_t msb, uint8_t lsb) {
return (static_cast<uint16_t>(msb) << 8) | (static_cast<uint16_t>(lsb));
+20
View File
@@ -55,6 +55,26 @@ TEST(HelpersTest, Ilog10RoundTripMatchesLog10) {
}
}
TEST(HelpersTest, Nibbles) {
EXPECT_EQ(high_nibble(0xA5), 0xA);
EXPECT_EQ(low_nibble(0xA5), 0x5);
EXPECT_EQ(high_nibble(0x0F), 0x0);
EXPECT_EQ(low_nibble(0xF0), 0x0);
static_assert(high_nibble(0xFF) == 0xF && low_nibble(0xFF) == 0xF, "usable in constant expressions");
}
TEST(HelpersTest, EncodeUint12) {
EXPECT_EQ(encode_uint12(0x12, 0x3), 0x123);
EXPECT_EQ(encode_uint12(0xFF, 0xF), 0xFFF);
EXPECT_EQ(encode_uint12(0x00, 0x0), 0x000);
EXPECT_EQ(encode_uint12(0x12, 0xA3), 0x123);
// A touch record byte packing the low nibbles of X (high) and Y (low)
const uint8_t shared = 0x5C;
EXPECT_EQ(encode_uint12(0x34, high_nibble(shared)), 0x345);
EXPECT_EQ(encode_uint12(0x67, low_nibble(shared)), 0x67C);
static_assert(encode_uint12(0xAB, 0xC) == 0xABC, "usable in constant expressions");
}
TEST(HelpersTest, SignExtend) {
EXPECT_EQ(sign_extend<24>(0x000000), 0);
EXPECT_EQ(sign_extend<24>(0x7FFFFF), 8388607);