Main      Site Guide    
Message Forum
Re: Decimal to Binary Conversion
Posted By: [Spacebar], on host 142.59.135.51
Date: Sunday, November 26, 2000, at 20:00:23
In Reply To: Decimal to Binary Conversion posted by gremlinn on Sunday, November 26, 2000, at 19:48:53:

> Given a positive integer (X) in decimal, here's a series of steps to convert it to binary (the current digit starts in the digit representing 2^0):
>
> 1. If X is even, write '0' in the current digit; if X is odd, write '1' in the current digit and then subtract 1 from X.
>
> 2. Shift the current digit one place to the left.
>
> 3. If X = 0, you're done. Otherwise, divide X by 2 and go back to step 1.

Oooh, snazzy. I hadn't even thought about easy ways of expressing decimal numbers in binary before. I did write a program to do that once, but it used the "brute force" method since my primary objective in writing that program was to be /finished/ writing the program in five minutes -- I didn't care whether or not it was efficient!

This, of course, is the brute force method (starting with zeroes under all of the columns):

1. Find the biggest number that can be expressed as power of two, and that is less than X.

2. Subtract that number from X, and put a one in the column indexed by the base two logarithm of that number.

3. Repeat until X=0.

-SB