C/C++ function to Convert Hex String to Decimal Number


In C/C++ header file stdlib.h there is a function strtol which will convert given string to a long int at the specified base. The function prototype takes three parameters. The first parameter is type of const char* which specifies the source string. The second parameter is char ** whose value is set to the next character position after the numerical value is obtained, in which case, set this to NULL to disregard this value. The third parameter specifies the base which is valid from 2 to 36. If the base is o then the base is determined by the source string automatically.

1
long int strtol (const char* str, char** endptr, int base);
long int strtol (const char* str, char** endptr, int base);

The function first ignores the starting white-spaces and take as many valid number characters as possible. If it is not a valid number string, then no conversion will be performed.

We can easily wrap this function to convert a given Hex (base 16) string to Decimal (base 10).

1
2
3
4
inline
int getHex(string hexstr) {
    return (int)strtol(hexstr.c_str(), 0, 16);
}
inline
int getHex(string hexstr) {
    return (int)strtol(hexstr.c_str(), 0, 16);
}

The following gives you the idea of the usage of the second parameter, which is especially useful in walking through the source strings that contains several numbers. After each conversion, the second parameter points to the next number.

1
2
3
4
5
6
7
8
9
  char szNumbers[] = "2001 60c0c0 -1101110100110100100000 0x6fffff";
  char * pEnd;
  long int li1, li2, li3, li4;
  li1 = strtol (szNumbers, &pEnd, 10);
  li2 = strtol (pEnd, &pEnd, 16);
  li3 = strtol (pEnd, &pEnd, 2);
  li4 = strtol (pEnd, NULL, 0);
  printf ("The decimal equivalents are: %ld, %ld, %ld and %ld.\n", li1, li2, li3, li4);
  return 0;
  char szNumbers[] = "2001 60c0c0 -1101110100110100100000 0x6fffff";
  char * pEnd;
  long int li1, li2, li3, li4;
  li1 = strtol (szNumbers, &pEnd, 10);
  li2 = strtol (pEnd, &pEnd, 16);
  li3 = strtol (pEnd, &pEnd, 2);
  li4 = strtol (pEnd, NULL, 0);
  printf ("The decimal equivalents are: %ld, %ld, %ld and %ld.\n", li1, li2, li3, li4);
  return 0;

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
328 words
Last Post: Using Forecast function in excel to predict or calculate a future value along a linear trend by using existing values
Next Post: VBScript Coding Exercise - Insertion Sorting Algorithm

The Permanent URL is: C/C++ function to Convert Hex String to Decimal Number

Leave a Reply