Web Development for 2012

Alexander Dickson - Web Developer covering PHP, jQuery / Javascript, XHTML, CSS, more

Converting hexadecimal to decimal in C

Published on Friday, 20th August 2010.

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; }
Write the function htoi(s), which converts a string of hexadecimal 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.

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

Comment Details

Your email will never be displayed. If you have a gravatar, it will be displayed.

Note: Your comment may require approval before it is posted to the site.

Stack Overflow Profile

view full profile »

About

I'm a web developer from the Sunshine Coast, Australia. more »