Converting hexidecimal digits to integer value
I am working on K&R's Exercise 2-3. The problem is as followed:
Write a function htoi(s), which converts a string of hexidecimal digits (including an optional 0x or 0X) into its equivalent integer value. The allowable digits are 0 through 9, a through f, and A through F.
I have written the code (skipping the optional 0x or 0X) for this function and I'm pretty sure I'm correct, but I want someone to double check my work and let me know if there is anything I can improve or work on. Thank you in advance!
Here is my code:
Code:
int htoi(char s[]){
int i, n;
i = 0;
n = 0; // integer value to be returned
for(i = 0; s[i] >= '0' && s[i] <= '9'; ++i){
n = 16 * n + (s[i] - '0');
if(s[i] >= 'a' && s[i] <= 'f')
n = 16 * n + (s[i] - 'a');
else if(s[i] >= 'A' && s[i] <= 'F')
n = 16 * n + (s[i] - 'A');
else
return 0; // not a valid hex digit
}
return n;
}