hex to dec in string

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:)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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
    else if (s[i] >= 'A' && s[i] <= 'F')
    {
      dec += (s[i] - 55)*base;

      // base * 16
      base = base * 16;
    }
  }
  return dec;
}
Last edited on
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, ...
Last edited on
I got it, thank you very much:)
c++ can convert string hex to int for you, if you didnt know that. This is good for educational purposes, like writing your own containers.
Last edited on
Topic archived. No new replies allowed.