Shop OBEX P1 Docs P2 Docs Learn Events
Double Precision Binary to BCD Conversion — Parallax Forums

Double Precision Binary to BCD Conversion

I couldn't find extended precision binary-to-BCD conversion in spin, so here one is. It does up to (2^64)-1. You give it two longs and it return 20 bytes of BCD. I checked it against all 64 powers of two, which it got correct. The method is discussed in the comment section of the code, but basically it repeatedly subtracts powers of 10.

Comments

  • There's another method of converting whereby you check all of the nibbles of the result, one nibble at a time. For any nibble that is greater than four, add three. Then shift all of the registers--result and source--up one bit and check again. Repeat until every bit has been shifted into the result.
    16-bit example:                       BCD_value           Hex_value
            Start                   0000_0000 0000_0000|0000_0100 1101_0010   1234 = $04D2
       1    Shift left                                 |0000_1001 1010_010
       2    Shift left                                 |0001_0011 0100_10
       3    Shift left                                 |0010_0110 1001_0
       4    Shift left                                 |0100_1101 0010
       5    Shift left                                 |1001_1010 010
       6    Shift left                                1|0011_0100 10
       7    Shift left                               10|0110_1001 0
       8    Shift left                              100|1101_0010
       9    Shift left                             1001|1010_010
            Add 3 to 1st nibble (>4)               1100|1010_010
      10    Shift left                           1_1001|0100_10
            Add 3 to 1st nibble                  1_1100|0100_10
      11    Shift left                          11_1000|1001_0
            Add 3 to 1st nibble                 11_1011|1001_0               
      12    Shift left                         111_0111|0010
            Add 3 to 2nd nibble               1010_0111|0010
            Add 3 to 1st nibble               1010_1010|0010
      13    Shift left                      1 0101_0100|010
            Add 3 to 2nd nibble             1 1000_0100|010
      14    Shift left                     11 0000_1000|10
            Add 3 to 1st nibble            11 0000_1011|10
      15    Shift left                    110 0001_0111|0
            Add 3 to 3rd nibble          1001 0001_0111|0
            Add 3 to 1st nibble          1001 0001_1010|0
      16    Shift left                 1_0010 0011_0100|   = $1234
    
    Attached 64-bit Spin and PASM routines.
Sign In or Register to comment.