go to previous page   go to home page   go to next page

Answer:

Perform modulo division by 2 on the integer.


Decimal to Base 2 Algorithm

So now you can find the two rightmost bits of N.

For example, say that N is 13. Then N mod 2 is 1 and the binary starts out as: _ _ _ 1 .

To get the next bit, do this: 13 div 2 is 6, and 6 mod 2 is 0.

So a 0 is added to the binary: _ _ 0 1 .

To get the third bit, do this: 6 div 2 is 3, and 3 mod 2 is 1.

So a 1 is added to the binary: _ 1 0 1 .

To get the fourth bit, do this: 3 div 2 is 1, and 1 mod 2 is 1.

So a 1 is added to the binary: 1 1 0 1 .

To get a bit of the binary representation of a number, do integer division of the number. The remainder (the mod) is the bit, and the quotient (the div) is the new number. Do this enough times and you get all the bits of the integer. The bits come out in order from right to left.

Here is that process described in pseudo-code. The algorithm converts number from decimal to base 2 representation.

Algorithm: Convert a positive integer
from base 10 to Binary Representation
number = positive integer ;
bitstring = ""

while (number > 0 )
{
  bit      = number mod 2 ;
  put bit to the left of the bitstring ;
  quotient = number div 2 ;
  number = quotient ;
}

This is the same algorithm that was presented in chapter 7 (but there the algorithm was for any base B).


QUESTION 4:

Of course, you want to see this algorithm in action.

What is the rightmost bit of the binary representation of 23?


go to previous page   go to home page   go to next page