# Converting hex to dec problems

• 10-16-2003
Dragoon_42
Converting hex to dec problems
For some reason my algorithm to convert a hexadecimal number into a decimal number doens't work and I cna't figure it out. Any help would be appreciated.
Code:

```#include<string.h> #include<math.h> #include<stdio.h> //dest is a character array that holds my hexedecimal string int todecimal(char *dest) {         int pos, sum, power_of_16;                 //pos is the current element in the dest array                 pos=strlen(dest);         power_of_16=0;                 sum=0;         do{                 --pos;                 if(dest[pos]<=9)                         sum+=dest[pos]*pow(16,power_of_16);                 switch(dest[pos]){                         case 'a': sum+=10*pow(16,power_of_16);                                 break;                         case 'b':sum+=11*pow(16,power_of_16);                                 break;                         case 'c':sum+=12*pow(16,power_of_16);                                 break;                         case 'd':sum+=13*pow(16,power_of_16);                                 break;                         case 'e':sum+=14*pow(16,power_of_16);                                 break;                         case 'f':sum+=15*pow(16,power_of_16);                                 break;                         default: /*do nothing*/                                 break;                 }                 power_of_16++;         }while(pos!=0);                 return sum; }```
• 10-16-2003
Dave_Sinkula
>if(dest[pos]<=9)

The character value of a text digit may not be a decimal value. For example, an ASCII '4' is equal to 0x34, which is equal to 52. You may want to use the following.
Code:

```if ( dest[pos]-'0'<=9 )   sum+=(dest[pos]-'0')*pow(16,power_of_16);```
• 10-16-2003
Dragoon_42
May I ask what that does exactly? I'm new to C, but have been using C++ for a couple of years. Let me guess, it subtracts the ASCII value of zero from the ASCII value of dest[pos] and that should fix it?
• 10-16-2003
Dave_Sinkula
Code:

```#include<stdio.h> int main(void) {   int i;   for(i = '0'; i <= '9'; ++i)   {       printf("i = '%c' = %d, i - '0' = %d - %d = %d\n", i, i, i, '0', i - '0');   }   return 0; } /* my output i = '0' = 48, i - '0' = 48 - 48 = 0 i = '1' = 49, i - '0' = 49 - 48 = 1 i = '2' = 50, i - '0' = 50 - 48 = 2 i = '3' = 51, i - '0' = 51 - 48 = 3 i = '4' = 52, i - '0' = 52 - 48 = 4 i = '5' = 53, i - '0' = 53 - 48 = 5 i = '6' = 54, i - '0' = 54 - 48 = 6 i = '7' = 55, i - '0' = 55 - 48 = 7 i = '8' = 56, i - '0' = 56 - 48 = 8 i = '9' = 57, i - '0' = 57 - 48 = 9 */```
• 10-16-2003
Dragoon_42
Thank you very much! Now I'll move on to trying to convert signed decimals to 2's complement binary. I really appreciate the help!