mov 1,ax

Today I learned or maybe learned again a long forgotten algorithm for converting decimal numbers to binary, courtesy of Hyde’s The Art of Assembly Language.

Start with a number, say 347 and use the following algorithm:

  • If the number is even, emit a zero, if it’s odd, emit a one.

So 347 is odd, we emit a 1.

  • Divide the number by two and throw away any fractional component or remainder.

347 / 2 = 173.5 … 173

  • If the quotient is zero, the algorithm is complete.

173 is not zero, we’re not done.

  • If the quotient is not zero and is odd, emit a 1 before the current string; if the number is even, prefix the binary string with zero.

We’re at 11.

  • Go back to step two and repeat.

173 / 2 = 86.5 … 86

011

86 / 2 = 43

1011

43 / 2 = 21.5 … 21

11011

21 / 2 = 10.5 … 10

011011

10 / 2 = 5

1011011

5 / 2 = 2.5 … 2

01011011

2 / 2 = 1

101011011

1 / 2 = 0.5

We’re done. 347 in base 10 is 101011011 in base 2.

Written on September 3, 2017