String to Dec conversion

I currently have:
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
int	converttoint(string strtodec)											
{
	int num,sum=0;
	for(int i=0; i<strtodec.length(); i++)
	{
		switch(strtodec[i])
		{
		case '0': num=0;break;
		case '1': num=1;break;
		case '2': num=2;break;
		case '3': num=3;break;
		case '4': num=4; break;
		case '5': num=5; break;
		case '6': num=6;break;
		case '7': num=7;break;
		case '8': num=8;break;
		case '9': num=9;break;
		case 'A': num=10;break;
		case 'B': num=11;break;
		case 'C': num=12; break;
		case 'D': num=13;break;
		case 'E': num=14;break;
		case 'F': num=15;break;
		}
		sum+=(int)pow(16.0,3-i)*num;
	}
	return sum;
}


Is there another way to do this? Oh and the string value is hex.
Last edited on
If your string represents a hex array then it'd be difference.

e.g
1
2
3
string someHex = "EDF"; // How I see your method?
// vs
string someHex = 0x41; // Shud be an array of unsigned chars instead. 


If yours is the first case, then the way you have done it will suffice. Although your math is wrong.

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
int converttoint(string strtodec)                     //function to check if the operand is correct
{
  int num,sum=0;
  for(int i=strtodec.length()-1; i>=0; i--)
  {
    switch(strtodec[i])
    {
    case '0': num=0;break;
    case '1': num=1;break;
    case '2': num=2;break;
    case '3': num=3;break;
    case '4': num=4; break;
    case '5': num=5; break;
    case '6': num=6;break;
    case '7': num=7;break;
    case '8': num=8;break;
    case '9': num=9;break;
    case 'A': num=10;break;
    case 'B': num=11;break;
    case 'C': num=12; break;
    case 'D': num=13;break;
    case 'E': num=14;break;
    case 'F': num=15;break;
    }
    sum += (int)num * pow(16, strtodec.length() - (i+1));
  }
  return sum;
}
I think I want it as a hex array. This is something I came up with just testing it out. Thanks for the correction on the math.
Then you wanna use an array of unsigned chars, and the similar math to sum += (int)num * pow(16, strtodec.length() - (i+1)); when iterating through it.
Cleaner Version:

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
#include <iostream>
#include <string>
#include <math.h>

using namespace std;

int converttoint(string input)                     //function to check if the operand is correct
{
  int sum = 0;
  for(int i = input.length()-1; i >= 0; i--) {
    // Change Off-Set 
    if ((input[i] >= '0') && (input[i] <= '9'))
      input[i] -= '0';
    else if(toupper(input[i] >= 'A') && (toupper(input[i] <= 'F')))
      input[i] = toupper(input[i]) - 'A' + 10;
    else
      return 0; // Do Some error catching

    sum += (int)input[i] * (int)pow(16, input.length() - (i+1));
  }
  return sum;
}

int main() {
  cout << converttoint("AB") << endl;

  return 0;
}
Last edited on
Topic archived. No new replies allowed.