User Tools

Site Tools


Converting binary to BCD

by Richard Russell, June 2007

Converting binary (base-2) to BCD (base-10) is a frequently needed operation, especially when printing out numeric results in decimal. There are standard methods of doing this in assembly language, mostly using the DAA (Decimal Adjust after Addition) instruction, but if it is acceptable to use the Floating Point Unit (Numeric Coprocessor) then there is a much easier method.

The assembler code below converts the 32-bit (4 byte) signed binary number stored in memory at address bin% to an 18-digit packed BCD number (plus sign) stored in memory at address bcd%:

      fild dword [bin%]
      fbstp tbyte [bcd%]

Note that ten bytes of memory must be allocated for the BCD number, and that the last byte contains just a sign bit in the MSB. The remaining seven bits in that byte should be ignored.

The following test program demonstrates the use of this code:

        DIM bin% 3, bcd% 9
          INPUT "Enter number: " !bin%
          CALL bin2bcd
          PRINT "BCD equivalent is: ";~!bcd%
        DEF PROCassemble
        LOCAL P%, L%
        DIM P% 12, L% -1
        [OPT 10
        fild dword [bin%]
        fbstp tbyte [bcd%]

In this case only the final 8 digits of the BCD number are printed.

This website uses cookies for visitor traffic analysis. By using the website, you agree with storing the cookies on your computer.More information
converting_20binary_20to_20bcd.txt · Last modified: 2018/04/13 10:36 by richardrussell