[comp.binaries.ibm.pc.d] Bin-ASCII Conversion corrected

kirchner@informatik.uni-kl.de (Reinhard Kirchner) (02/21/91)

Hello,
recently I posted an algorithm for conversion of arbitrary lenght binary
numbers to decimal into this group ( I at least think so, I can't find
my original anymore )

Anyway, this posting was WRONG. I did this more than 10 years ago, and
chemical memory is analogue technology, so bits weaken and drop out....

Now I looked into my notices, and here is the correct algorithm.

As I told, you shift the binary into the bcd or ASCII number. In memory
we need therefore

|----+----+----+----+----+----+----|---------------|
      decimal number                  binary number

We now shift this whole thing left so often as the binary has bits. Then
the binary bits cross the border to the decimal number. There now we
have to make a DECIMAL shift. This means:
For each digit: if it is >= 5 add a constant which generates a bit in the
highest position of the digit and subtracts 5 from the value.
For bcd this constant is 3 ( 8-5 ), for bytes it is 123 ( 128-5 ).
Now enough theory, lets have an example. We convert 0010 0000 0000 ( 512 ).

Memory:
00 00 00 00|0010 0000 0000      decimal side in hex, binary in bits
                                not so much to type
we have to shift 12 times for 12 binary bits

00 00 00 00|0100                1  I leave out unimportant ( zero ) bits
00 00 00 00|1000                2
00 00 00 01|0000                3
00 00 00 02|                    4
00 00 00 04|
00 00 00 08|                    6  now 8>=5, add 123 ( hex 7b )
00 00 00 83|
00 00 01 06|                    7  6>=5, add
00 00 01 81|
00 00 03 02|                    8
00 00 06 04|                    9  6>=5, add
00 00 81 04|
00 01 02 08|                   10  8>=5, add
00 01 02 83|
00 02 05 06|                   11  6>=5, add ( already 256, half of 512 ! )
                                   5>=5, add also
00 02 80 81|
00 05 01 02|                   12 last shift, and we have 5 1 2 !!!!
 
now simply add '0' to have a perfect ASCII string

On some machines it is better to add 256-5 = 251 to get the carry-bit direct
into the carry flag. It may also be better to compare against 10 and add 251,
to get the already shifted decimal carry into the carry bit, where it may
be shifted out into the next digit.

All are variations of the same idea: shift the binary number binary
                                     and the decimal number decimal

There is of course the reverse algorithm to convert decimal to binary by
shifting right and doing some clever subtracting. This is not so important
since we can easily multiply binaries by ten with shifting and adding.
Anyway, I leave this exercise to the reader ....

Reinhard Kirchner
Univ. Kaiserslautern, Germany
kirchner@uklira.informatik.uni-kl.de