Decimal to Binary Algorithm

advertisement
Here is a simple algorithm for converting decimal numbers to binary using repeated division by 2.
Algorithm for converting decimal numbers to binary
The easiest way represent this algorithm is with a table.
n
35
17
8
4
2
1
n/2n%2
17 1
8
1
4
0
2
0
1
0
0
1
1. Put the number you want to convert in the left column (35 in this example) and put the
value of that number divided by 2 (using integer division) in the next column, and the
remainder of that division (result of the "mod" operator) in the right column. In the
example below, we'll start with the number 35. 35/2 is 17, with remainder 1.
2. In the next row, copy the middle value (17) into the left, and fill out the other columns
appropriately for this number. 17/2 is 8, with remainder 1.
3. Continue this process until the number in the n/2 column is zero. You could continue,
but it will soon be obvious that all further digits from then on will be zeros.
4. The resulting binary value is in the last column, but must be read from bottom to top.
The binary representation of 35 is 100011.
Another Example
Let's convert 6 to binary. Working thru the algorithm with this value gives a binary
representation of 110.
n
6
3
1
n/2n%2
3
0
1
1
0
1
Hint: Visual Basic has a built in function called strReverse. This function will flip the order of any string. For instance if
srtNum=110001 then strReverse(strNum) would give us 100011. How would this be useful in this program?
Download