Unsigned Integer to BCD conversion?

前端 未结 10 1403
囚心锁ツ
囚心锁ツ 2020-12-11 05:01

I know you can use this table to convert decimal to BCD:

0 0000

1 0001

2 0010

3 0011

4 0100

5 0101

6 01

10条回答
  •  遥遥无期
    2020-12-11 05:19

    Just simplified it.

    #include 
    #define uint unsigned int
    
    uint Convert(uint value, const uint base1, const uint base2)
    {
        uint result = 0;
        for (int i = 0; value > 0; i++)
        {
            result += value % base1 * pow(base2, i);
            value /= base1;
        }
        return result;
    }
    
    uint FromBCD(uint value)
    {
        return Convert(value, 16, 10);
    }
    
    uint ToBCD(uint value)
    {
        return Convert(value, 10, 16);
    }
    

提交回复
热议问题