I must implement a function with the following prototype:
int base10(char *n, int b)
the objective is that the array passed as a parameter contains in each index a digit of a number in base b, which must be returned in base 10. So far I have written the following.
int val(char n){
if(n >= '0' && n<='9'){
return (int)n;
}else{
switch (n) {
case 'A': return 10;
case 'B': return 11;
case 'C': return 12;
case 'D': return 13;
case 'E': return 14;
case 'F': return 15;
case 'G': return 16;
}
}
}
int base10(char *n, int b){
int tamano,resultado=0;
tamano = //no se como
printf("%d", tamano);
for(int i=0;i<tamano;i++) resultado += val(n[i])*pow(b,i);
return resultado;
}
To convert from base x to base 10 I must multiply each digit by the base raised to its position in the number, my problem is that I do not know how many operations I must carry out because they do not give me the number of digits (or size of the array) as information ).
It is not possible to solve that problem without knowing the size of the array. Either directly (they give you the numerical size directly) or indirectly (the array has a terminator like
'\0'
).I notice that in your code each element contains not a single digit number in base b, but an ASCII character that represents a digit in base b.
The distinction is important because it indicates that it
char *n
is surely a standard C string. And the standard convention in C is to use a terminator'\0'
.Therefore the solution is to traverse the array until finding an element that is
'\0'
The code above will overflow for numbers that exceed the capacity of
int
and also has no error handling, but that's a matter for another question.Otherwise the function
val
is not correct.If the parameter
char n
is '0' the result of(int)n
is not 0 but 48.The reason is that n is a variable of type char that contains, by convention, a number that represents a character according to the ASCII code table . As you can see in the table above, the number 48 represents the character
'0'
.To convert from an ASCII character to its numeric value, simply subtract 48.
And while converting the letters 'A' to 'G' with a switch is fine, it can be done with less code using the same technique.
Although the
val
above function contains some error handling it is still not enough. The number "JJ019A" is not valid in base 10 and it is valid in base 30, but the code above does not detect that.