1. ## Base 16

I can't spot my mistake, I've also done the problem on paper and it should return the right result, instead it's giving me 6. Could you help me?
Code:
```/* Write a function that given a natural number computes the value resulting from the digits of its decimal representation when interpreted as a hexadecimal number.
Example: f(312) = 3 * 256 + 1 * 16 + 2 = 786
Hint: use the same recursive decomposition, but when reconstructing the number, use the new base (16).
*/

#include <stdio.h>
#include <math.h>
int hex(int n, int i){
i=0;
if(n==0)
return 0;
else
return (n%10)*pow(16,i)+hex(n/10,i+1);

}

int main()
{
int a=312;
int i=0;
printf("The number %d in base 16 is %d\n", a, hex(a,i));
return 0;
}``` 2. I guess your basic problem is that you set i to 0 every invocation.
However there's a more general problem. You can't accept an actual hex input since you can only input digits 0 to 9 and not A to F.
Your input should be a string to allow all hex-digit characters.
Code:
```#include <stdio.h>
#include <ctype.h>

int hex2dec(const char *h) {
int dec = 0;
for ( ; isxdigit(*h); ++h) { // note that isxdigit('\0') is false
int value = isdigit(*h) ? *h - '0'
: isupper(*h) ? *h - 'A' + 10
: *h - 'a' + 10;
dec = dec * 16 + value;
}
return dec;
}

int main() {
const char *a = "312";
printf("The base-16 number %s is %d decimal\n", a, hex2dec(a));
a = "ABC";
printf("The base-16 number %s is %d decimal\n", a, hex2dec(a));
return 0;
}``` Popular pages Recent additions base, i=0;, int, number, return 