Tips and Tricks: Converting numbers between bases faster
If you find the methods of conversion traditionally taught at school boring and slow, you are not the only one.
From Binary to Decimal
Tip 1: Double dabble
Consider the integer DnDn-1...D1D0 with (n+1) digits.
Starting with the most significant bit, carry out the following algorithm:
- Result = Dn
- Result = Result * 2
- Result = Result + Dn-1
- Repeat steps 2 and 3 until you have added the least significant bit to ResultD0to Result
For example, the number 101001012 = 16510
- Result = 1
- Result = Result * 2 = 2
- Result = Result + 0 = 2
- Result = Result * 2 = 4
- Result = Result + 1 = 5
- Result = Result * 2 = 10
- Result = Result + 0 = 10
- Result = Result * 2 = 20
- Result = Result + 0 = 20
- Result = Result * 2 = 40
- Result = Result + 1 = 41
- Result = Result * 2 = 82
- Result = Result + 0 = 82
- Result = Result * 2 = 164
- Result = Result + 1 = 165
This method is essentially the reverse of the repeated division algorithm that we are used to for converting from base 10 and base 2.
Tip 2: Mind the zeros!
Who said you should always use the positional weight of 1s in your calculations? If there are fewer 0s than 1s in the number, consider the following approach:
For example, in the number 110111012, there are only 2 zeros. Knowing that 111111112 = 25510, and that the missing 1s in 110111012 have a simple sum of 32 + 2 = 34. It's relatively easier to calculate the difference between 255 and 34 than to add 128, 64, 16, 8, 4 and 1. Both lead to the same result.
That's it for the time being. Stay tuned for more tips!
Coming up:
- Two's complement conversion tips
- Derivation of the iterative formula
Comments
Post a Comment