I have a function to convert uint16_t to BCD.
uint16_t uint162BCD(uint16_t value)
{
uint16_t b_val = 0;
unsigned int shift = 0;
while (shift / 8 < sizeof(bcd))
{
b_val = static_cast<uint16_t>(b_val + ((value % 10) << shift));
value = value / 10;
shift = shift + 4;
}
return b_val;
}
I did a small unit test with the following values
ASSERT_EQ(uint162BCD(0), (uint16_t) 0x0);
ASSERT_EQ(uint162BCD((uint16_t) 1), (uint16_t) 0x1);
ASSERT_EQ(uint162BCD((uint16_t) 12), (uint16_t) 0x12);
ASSERT_EQ(uint162BCD((uint16_t) 123), (uint16_t) 0x123);
ASSERT_EQ(uint162BCD((uint16_t) 56), (uint16_t) 0x56);
These seems to convert as expected. However if I do this.
ASSERT_EQ(uint162BCD((uint16_t) 0056), (uint16_t) 0x56);
It doesn't work. I would expect the same value as 0x56. What am I doing wrong?
ASSERT_EQ(uint162BCD((uint16_t) 0056), (uint16_t) 0x56);
Literal integers, in C or C++, that start with "0" are interpreted as octal numbers. "0056" is what we humans, with ten fingers, call "46".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With