In any positional number system, any number (even fractional numbers) is represented as sum(di * basei), where di is the digit in the i
-th place (counted from right to left) with d0 being the digit in the first position left of the decimal point. For ease of its evaluation evaluation, the sum could be "folded" using Horner's rule:
(((d[n]*base + d[n-1])*base + d[n-2])*base + d[n-3])*base + ...
The good thing about this one is that one could start from the most significant digit and work his was to the right which follows the way digits are ordered in memory or file strings.
string number = "1A";
int decimal = 0;
for (string::const_iterator it = number.begin(); it != number.end(); it++)
decimal = decimal * base + to_int(*it);
to_int()
should take care of converting a character to its decimal value, e.g.
int to_int (char d) {
if ('0' <= d && d <= '9')
return d - '0';
else if ('A' <= d && d <= 'J')
return 10 + (d - 'A');
else
throw some error
}
C++ provides the convenient stoi()
function which does the math for you:
#include <string>
#include <iostream>
using namespace std;
int main (void) {
string number = "1A";
cout << number << " in decimal is " << stoi(number, 0, 20) << endl;
}
Compile and run:
$ clang++ -o visc visc.cc && ./visc
1A in decimal is 30
In C one could use strtol()
with the base set to 20. But it is supposed to be used in input tokenizers and modifies its input argument so care should be taken.
In Python the string
module provides atoi()
with selectable base:
>>> from string import atoi
>>> atoi("1A", 20)
30
Other languages provide similar conversion functions too, mostly found in their string processing libraries.