3

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?

Tas
  • 7,023
  • 3
  • 36
  • 51
liv2hak
  • 14,472
  • 53
  • 157
  • 270

1 Answers1

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

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
  • is there an escape sequence to make it not interpret as octals. I mean my situation is that 0056 is a valid number (decimal) – liv2hak Aug 05 '19 at 02:13
  • 4
    Assuming that there was some way to express "0056" as a decimal number, it would accomplish absolutely nothing, whatsoever. There is only one number called "56", and whether specifying "56" or "0056", the end result is exactly the same: a two byte value containing 0 in the first byte, and 56 in the 2nd byte (because of the `uint16_t` that gets slapped in front of it). That's what your C++ compiler will spit out. Whether your code specified "56", or "0056" in some form or fashion, the compiled code will be identical. – Sam Varshavchik Aug 05 '19 at 02:16