Question

I'm trying to write a program in C that converts hexadecimal numbers to integers. I've written successfully a program that converts octals to integers. However, the problems begin once I start using the letters (a-f). My idea for the program is ads follows:

  1. The parameter must be a string that starts with 0x or 0X.

  2. The parameter hexadecimal number is stored in a char string s[].

  3. The integer n is initialized to 0 and then converted as per the rules.

My code is as follows (I've only read up to p37 of K & R so don't know much about pointers) :

/*Write a 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.*/

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <ctype.h>

int htoi(const char s[]) { //why do I need this to be constant??
    int i;
    int n = 0;
    int l = strlen(s);
    while (s[i] != '\0') {
        if ((s[0] == '0' && s[1] == 'X') || (s[0] == '0' && s[1] == 'x')) {
            for (i = 2; i < (l - 1); ++i) {
                if (isdigit(s[i])) {
                    n += (s[i] - '0') * pow(16, l - i - 1);
                } else if ((s[i] == 'a') || (s[i] == 'A')) {
                    n += 10 * pow(16, l - i - 1);
                } else if ((s[i] == 'b') || (s[i] == 'B')) {
                    n += 11 * pow(16, l - i - 1);
                } else if ((s[i] == 'c') || (s[i] == 'C')) {
                    n += 12 * pow(16, l - i - 1);
                } else if ((s[i] == 'd') || (s[i] == 'D')) {
                    n += 13 * pow(16, l - i - 1);
                } else if ((s[i] == 'e') || (s[i] == 'E')) {
                    n += 14 * pow(16, l - i - 1);
                } else if ((s[i] == 'f') || (s[i] == 'F')) {
                    n += 15 * pow(16, l - i - 1);
                } else {
                    ;
                }
            }
        }
    }
    return n;
}


int main(void) {
    int a = htoi("0x66");
    printf("%d\n", a);
    int b = htoi("0x5A55");
    printf("%d\n", b);
    int c = htoi("0x1CA");
    printf("%d\n", c);
    int d = htoi("0x1ca");
    printf("%d\n", d);
} 

My questions are:

1. If I don't use const in the argument for htoi(s), i get the following warnings from the g++ compiler :

2-3.c: In function ‘int main()’: 2-3.c:93:20: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings] 2-3.c:97:22: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings] 2-3.c:101:21: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings] 2-3.c:105:21: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]

Why is this?

2.Why is my program taking so much time to run? I haven't seen the results yet.

3.Why is it that when I type in cc 2-3.c instead of g++ 2-3.c in the terminal, I get the following error message:

"undefined reference to `pow'"

on every line that I've used the power function?

4. Please do point out other errors/ potential improvements in my program.

Was it helpful?

Solution

If I don't use const in the argument for htoi(s), i get the following warnings from the g++ compiler

The const parameter should be there, because it is regarded as good and proper programming to never typecast away const from a pointer. String literals "..." should be treated as constants, so if you don't have const as parameter, the compiler thinks you are casting away the const qualifier.

Furthermore, you should declare all pointer parameters that you don't intend to modify the contents of as const, Google the term const correctness.

Why is my program taking so much time to run? I haven't seen the results yet.

I think mainly because you have made an initialization goof-up. int i; i contains rubbish. Then while (s[rubbish_value] != '\0'). This function can be written a whole lot better too. Start by checking for the 0x in the start of the string, if they aren't there, signal some error (return NULL?), otherwise discard them. Then start one single loop after that, you don't need 2 loops.

Note that the pow() function deals with float numbers, which will make your program a slight bit slower. You could consider using an integer-only version. Unfortunately there is no such function in standard C, so you will have to found one elsewhere.

Also consider the function isxdigit(), a standard function in ctype.h, which checks for digits 0-9 as well as hex letters A-F or a-f. It may however not help with performance, as you will need to perform different calculations for digits and letters.

For what it is worth, here is a snippet showing how you can convert a single char to a hexadecimal int. It is not the most optimized version possible, but it takes advantage of available standard functions, for increased readability and portability:

#include <ctype.h>

uint8_t hexchar_to_int (char ch)
{
  uint8_t result;

  if(isdigit(ch))
  {
    result = ch - '0';
  }
  else if (isxdigit(ch))
  {
    result = toupper(ch) - 'A' + 0xA;
  }
  else
  {
    // error
  }

  return result;
}

OTHER TIPS

Don't use a C++ compiler to compile a C program. That's my first advice to you.

Secondly const in a function parameter for a char * ensures that the programmer doesn't accidentally modify the string.

Thirdly you need to include the math library with -lm as stated above.

  1. a const char[] means that you cannot change it in the function. Casting from a const to not-const gives a warning. There is much to be said about const. Check out its Wikipedia page.
  2. --
  3. Probably, cc doesn't link the right libraries. Try the following build command: cc 2-3.c -lm

Improvements:

  1. Don't use pow(), it is quite expensive in terms of processing time.
  2. Use the same trick with the letters as you do with the numbers to get the value, instead of using fixed 'magic' numbers.
  3. You don't need the last else part. Just leave it empty (or put an error message there, because those characters aren't allowed).

Good luck!

About my remark about the pow() call (with the use of the hexchar_to_int() function described above, this is how I'd implement this (without error checking):

  const char *t = "0x12ab";
  int i = 0, n = 0;
  int result = 0;
  for (i = 2; i < strlen(t); i++) {
   n = hexchar_to_int(t[i]);

   result |= n; 
   result <<= 4;
  } 

  /* undo the last shift */
  result >>= 4;

I just worked through this exercise myself, and I think one of the main ideas was to use the knowledge that chars can be compared as integers (they talk about this in chapter 2).

Here's my function for reference. Thought it may be useful as the book doesn't contain answers to exercises.

int htoi(char s[]) {
    int i = 0;
    if(s[i] == '0') {
        ++i;
        if(s[i] == 'x' || s[i] == 'X') {
          ++i;
        }
    }

    int val = 0;

    while (s[i] != '\0') {
        val = 16 * val;
        if (s[i] >= '0' && s[i] <= '9')
            val += (s[i] - '0');
        else if (s[i] >= 'A' && s[i] <= 'F') 
            val += (s[i] - 'A') + 10;
        else if (s[i] >= 'a' && s[i] <= 'f')
            val += (s[i] - 'a') + 10;
        else {
            printf("Error: number supplied not valid hexadecimal.\n");
            return -1;
        }           
        ++i;
    }

    return val;
}

Always init your variables int i=0, otherwise i will contain a garbage value, could be any number, not necessary 0 as you expect. You're running the while statement in an infinite loop, that's why it takes forever to get the results, print i to see why. Also, add a break if the string doesn't start with 0x, will avoid the same loop issue when the user is used on a random string. As others mention you need to import the library containing pow function and declare your string with const to get rid of the warning.

This is my version of program for the question above. It converts the string of hex into decimal digits irrespective of optional prefix(0x or 0X). 4 important library functions used are strlen(s), isdigit(c), isupper(c), isxdigit(c), pow(m,n)

Suggestions to improve the code are welcome :)

/*Program  - 5d Function that converts hex(s)into dec -*/
#include<stdio.h>
#include<stdlib.h>
#include<math.h>                //Declares mathematical functions and macros
#include<string.h>              //Refer appendix in Page 249 (very useful)
#define HEX_LIMIT 10

int hex_to_dec(char hex[])      //Function created by me :)
{
   int dec = 0;                //Initialization of decimal value
   int size = strlen(hex);     //To find the size of hex array
   int temp = size-1 ;         //Pointer pointing the right element in array
   int loop_limit = 0;         //To exclude '0x' or 'OX' prefix in input

   if(hex[0]=='0' && ((hex[1]=='x')  || (hex[1]=='X')))
   loop_limit = 2;

   while(temp>=loop_limit)
   {
     int hex_value = 0;        //Temporary value to hold the equivalent hex digit in decimal

     if(isdigit(hex[temp]))
       hex_value = (hex[(temp)]-'0') ;
     else if(isxdigit(hex[temp]))
        hex_value =  (toupper(hex[temp])-'A' + 10);
     else{
        printf("Error: No supplied is not a valid hex\n\n");
        return -1;
      }

    dec += hex_value * pow(16,(size-temp-1));        //Computes equivalent dec from hex
    temp--;                    //Moves the pointer to the left of the array
   }
   return dec;
}

int main()
{
char hex[HEX_LIMIT];
printf("Enter the hex no you want to convert: ");
scanf("%s",hex);
printf("Converted no in decimal: %d\n", hex_to_dec(hex));

return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top