Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Unsigned Int to BCD [duplicate]

Tags:

c++

bcd

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?

like image 488
liv2hak Avatar asked Feb 17 '26 20:02

liv2hak


1 Answers

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".

like image 53
Sam Varshavchik Avatar answered Feb 19 '26 12:02

Sam Varshavchik