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.