0

I am trying to use strtol to convert a hex value into a decimal. It has been verified as a valid hex value before in the program, and now I am trying to convert it, but it keeps printing "0" for most values.

int convert_hexadecimal_address(char *hexadecimal) {
    printf("The character going in is %s\n", hexadecimal);
    long hex_int = strtol(hexadecimal, NULL, 10);
    printf("The long is %ld\n", hex_int);
    return hex_int;
}

What is wrong with this code?

Unihedron
  • 10,902
  • 13
  • 62
  • 72
  • 2
    `strtol(hexadecimal, NULL, 10);` --> `strtol(hexadecimal, NULL, 16);` – BLUEPIXY Aug 07 '14 at 10:17
  • Thank you - feel free to add that as an answer. But why, if I am converting to decimal base 10 would it need to be base 16? –  Aug 07 '14 at 10:18
  • You must specify the radix of the first argument. – BLUEPIXY Aug 07 '14 at 10:20
  • @user3844996 you are converting a string of characters *from* base 16 to a signed long integer. Integer types are not base 10, they're just integers. You can choose to represent an integer in any way you like. Natively they are base 2, actually, but it doesn't really matter; they represent a number. The function needs to know how to interpret the string you are giving it, not the format of the output (since the format of a `long` is already well known to the compiler). – J... Aug 07 '14 at 10:21
  • http://stackoverflow.com/questions/10156409/convert-hex-string-char-to-int – ani627 Aug 07 '14 at 10:22

3 Answers3

3

From strtol - C++ Reference:

Numerical base (radix) that determines the valid characters and their interpretation.
If this is 0, the base used is determined by the format in the sequence (see above).

So you should use:

long hex_int = strtol(hexadecimal, NULL, 16);
Community
  • 1
  • 1
László Ács
  • 149
  • 1
  • 9
0

If you want hex, say it:

long hex_int = strtol(hexadecimal, NULL, 10);

the last argument should be 16.

Wojtek Surowka
  • 20,535
  • 4
  • 44
  • 51
0

Syntax of strtol is-

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

If base is zero or 16, the string may then include a "0x" prefix, and the number will be read in base 16; otherwise, a zero base is taken as 10 (decimal) unless the next character is '0', in which case it is taken as 8 (octal).

Instead of this-

long hex_int = strtol(hexadecimal, NULL, 10);

you should use-

long hex_int = strtol(hexadecimal, NULL, 16);

For more info strtol

Sathish
  • 3,740
  • 1
  • 17
  • 28