Unsigned Integer to BCD conversion?

前端 未结 10 1351
囚心锁ツ
囚心锁ツ 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:27

    #include 
    
    /* Standard iterative function to convert 16-bit integer to BCD */
    uint32_t dec2bcd(uint16_t dec) 
    {
        uint32_t result = 0;
        int shift = 0;
    
        while (dec)
        {
            result +=  (dec % 10) << shift;
            dec = dec / 10;
            shift += 4;
        }
        return result;
    }
    
    /* Recursive one liner because that's fun */
    uint32_t dec2bcd_r(uint16_t dec)
    {
        return (dec) ? ((dec2bcd_r( dec / 10 ) << 4) + (dec % 10)) : 0;
    }
    

提交回复
热议问题