Good question and I'll explain the solution using a specific number as an example
e.g. input = "3894"
The numeric value of one character in the string can be obtained via a lookup table. Here I'll use a string as the lookup table.
LookupTable = "0123456789"
The important property of this lookup table is that the numeric value of a character is it's index in the table.
e.g. the value of the character '3' is 3 because it is found at LookupTable[3]
The total value of the input string could be obtained via the calculation
3894 = 4 + (9 * 10) + (8 * 100) + (3 * 1000)
but this can be rearranged so that it can be coded into a simple loop.
3894 = ((((((3 * 10) + 8) * 10) + 9) * 10) + 4)
public Int32 DecimalStrToInt(String input) {
const String LookupTable = "0123456789";
Int32 charValue;
Char c;
Int32 total = 0;
Int32 index = 0;
while (index < input.Length) {
c = input[index];
charValue = LookupTable.IndexOf(c);
total = (total * 10) + charValue;
index++;
}
return total;
}
It's a trivial task to modify the LookupTable and multiplier to handle any numeric base, e.g. base 16.
public Int32 HexStrToInt(String input) {
const String LookupTable = "0123456789ABCDEF";
Int32 charValue;
Char c;
Int32 total = 0;
Int32 index = 0;
while (index < input.Length) {
c = input[index];
charValue = LookupTable.IndexOf(c);
total = (total * 16) + charValue;
index++;
}
return total;
}
A real implementation would need to handle invalid inputs and result overflow.