Converting hexadecimal to decimal in C
The examples in K&R are starting to get a little tricky, at least for me, challenging the very way I approach problems. Dealing with a stream of characters forces me to think very differently in relation to solving a problem then I would in something high level like JavaScript or PHP. I only hope I am starting to think C, and hopefully haven't brought over any bad habits.
My code tonight will convert a hexadecimal number to decimal. It is Exercise 2-3 from page 46 in K&R. Once again, I'll assume I haven't learned the strlen() function yet, and know nothing about pointers. :P
int htoi(const char str[]) {
int length;
for (length = 0; str[length] != '\0' ; ++length) {}
int i, j;
int total = 0;
int power = 1;
for (i = 0, j = length - 1; str[i] != '\0'; ++i) {
// Throw away any leading 0, x or X
int leadingZero = (i == 0 && str[i] == '0');
int leadingX = (i == 1 && str[i] == 'x' || str[i] == 'X');
if (leadingZero || leadingX) {
continue;
}
char hexChar = str[j];
// Normalise capitals
if (hexChar >= 'A' && hexChar <= 'F') {
hexChar = hexChar + 'a' - 'A';
}
int dec;
if (hexChar >= '0' && hexChar <= '9') {
dec = (hexChar - '0') * power;
} else if (hexChar >= 'a' && hexChar <= 'f') {
dec = (hexChar - 'a' + 10) * power;
} else {
// Error, this is not a hexadecimal character
return -1;
}
total += dec;
power *= 16;
--j;
}
return total;
}The code is a bit messy, but it seems to works on the bunch of examples I have given it so far. I'm not sure if counting backwards is the best way to approach this problem, but I thought it suited the multiplication by the radix on each iteration.
Of course, I'd love some feedback :)
Comments
No comments yet.
Leave a Comment
Note: Your comment may require approval before it is posted to the site.