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 23. Then N mod 2 is 1 and the binary is _ _ _ _ 1.

To get the next bit, do this: 23 div 2 is 11 and 11 mod 2 is 1.

So the binary (so far) is _ _ _ 1 1.

To get one bit of the binary representation, divide the integer mod two. Then prepare for the next bit by dividing by two. 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 respresentation.

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

while (number > 0 )
{
  bit    = number mod 2 ;
  number = number div 2 ;
  put bit to the left of any previous bits
}

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?