can someone explain it how it works? for example, A4h,for int base, does it mean 16^0 which is 1? but there is not function for it to be 16^1, 16^2, or more. A4h to dec which is 4*16^0 + A*16^1 but in my loop, there is no function for the base++ but it works. I am so confused with it. I also want to rewrite it by myself. thank you so much:)
int hex_to_dec(string s)
{
// 16^0 = 1
int base = 1;
int dec = 0;
// from last character
for (int i = s.length() - 1; i >= 0; i--)
{
// converting character lies in '0'-'9'
// to integral 0-9 by subtracting 48 from
// ASCII value.
if (s[i] >= '0' && s[i] <= '9')
{
dec += (s[i] - 48)*base;
// base * 16
base = base * 16;
}
// converting character lies in 'A'-'F'
// to integral 10 - 15 by subtracting 55
// from ASCII value
elseif (s[i] >= 'A' && s[i] <= 'F')
{
dec += (s[i] - 55)*base;
// base * 16
base = base * 16;
}
}
return dec;
}
base is multiplied by 16 on each pass through the loop.
Initially base = 1 (line 4)
After the first loop, hence at start of the second loop, base = 16 (line 19 or line 29)
After that loop, base becomes 16 * 16 (line 19 or line 29 again)
And then 16 * 16 * 16
Etc.
You don't need an explicit operation to get "16 to the power of".
The code doesn't check that the string has no blanks or is legitimate hex, it relies on the hex characters being in upper case, 48 and 55 are magic numbers, ...