The idea is to isolate each digit and convert one digit at a time.
For example... break down a base-10 number:
"167" can be broken down to:
7*(10^0) = 7*1 = 7
6*(10^1) = 6*10 = + 60
1*(10^2) = 1*100 = + 100
-----
167 <-- base 10 result
This logic applies to numbers of any base N... just instead of 10, you use N. If, say, "167" was in base 8 and not base 10:
7*(8^0) = 7*1 = 7
6*(8^1) = 6*8 = + 48
1*(8^2) = 1*64 = + 64
-----
119 <-- base 10 result
The same logic can be applied for base 15. Just treat 'A'-'E' as 10-14, and multiply by (15^x)
In code -- this process can be even simpler. Simply keep a running sum of each digit, and multiply by the base between additions:
1 2 3 4 5 6
|
result = 0;
while( __digits_remaining__ )
{
result *= base;
result += next_digit;
}
| |
with that same base 10 example -- say we have 167:
"167"
sum = 0 next digit="1"
sum = (0*10)+1 = 1 next digit="6"
sum = (1*10)+6 = 16 next digit="7"
sum = (16*10)+7 = 167
This works with other bases as well. Same example, base 8:
sum = 0 next digit="1"
sum = (0*8)+1 = 1 next digit="6"
sum = (1*8)+6 = 14 next digit="7"
sum = (14*8)+7 = 119