Unsigned Integer to BCD conversion?

前端 未结 10 1383
囚心锁ツ
囚心锁ツ 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条回答
  •  Happy的楠姐
    2020-12-11 05:22

    If you want two decimal digits per byte, and "unsigned" is half the size of "unsigned long" (use uint32 and uint64 typedefs if you want):

    unsigned long bcd(unsigned x) {
      unsigned long ret=0;
      while(x>0) {
        unsigned d=x/10;
        ret=(ret<<4)|(x-d*10);
        x=d;
      }
      return ret;
    }
    

    This leaves you with the least significant (unit) decimal digit in the least significant half-byte. You can also execute the loop a fixed number (10 for uint32) of times, not stopping early when only 0 bits are left, which would allow the optimizer to unroll it, but that's slower if your numbers are often slow.

提交回复
热议问题