User Tools

Site Tools


converting_20binary_20to_20bcd

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
        PROCassemble
        REPEAT
          INPUT "Enter number: " !bin%
          CALL bin2bcd
          PRINT "BCD equivalent is: ";~!bcd%
        UNTIL FALSE
        END
 
        DEF PROCassemble
        LOCAL P%, L%
        DIM P% 12, L% -1
        [OPT 10
        .bin2bcd
        fild dword [bin%]
        fbstp tbyte [bcd%]
        ret
        ]
        ENDPROC

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

This website uses cookies. By using the website, you agree with storing cookies on your computer. Also you acknowledge that you have read and understand our Privacy Policy. If you do not agree leave the website.More information about cookies
converting_20binary_20to_20bcd.txt · Last modified: 2024/01/05 00:22 by 127.0.0.1