How do I convert a hex number as a string to an int as a string?

So, I have a comand-line program where a user types a number that they want to use in int form. The program takes the input string and converts it to an int. How do I make it take in something like 0xff and have the program interpret it as an int with a value of 255?

EDIT: Sorry, I should probably give more info about this function. I want the user to input one of four things: A regular int, a hex int, a percentage or a number with coefficients (something like GB or Mb), all as a char array. I need it to sort out the different types. An int will have nothing special, A hex int should start with 0x, A percentage should end in % and a coefficient number will end with its coefficient. The program needs to sort out the differences and output an int.

I want to do this using only the C standard libraries because cross compatibility is my programs biggest feature.
Last edited on
Using strtol seems to be the easiest way in good old C.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <stdlib.h>
#include <stdio.h>

#define HEX 16

int main()
{
  char szNumber[] = "0xFF";
  char *end;

  long num = strtol (szNumber,&end, HEX);
  
  printf ("%s = %u\n\n", szNumber, num);
  
  system("pause");
  return 0;
}
strtol() can figure out the difference between decimal and hex values based on the prefix. (Though beware of base 8 values which are assumed to start with a leading zero).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <stdio.h>
#include <stdlib.h>

int main()
{
    char input[] = "0x74CBB1 12345 555444 0xffff 0x12D687 3333";
    
    char *start = input;
    char *end   = start;
    
    long int n;
    
    while ( (n = strtol(start, &end, 0)) && (start != end) )
    {
        printf("%d\n", n);
        start = end;        
    }
    
    return 0;
}

Output:
7654321
12345
555444
65535
1234567
3333

Last edited on
Thanks, that's suuuper helpful. If strtol() can tell the difference, then why can't atio(), which is what I was previously using? What format would a base 8 digit be in? Like 0200 would be interpreted as 128?
Never mind, it doesn't matter. You have NO IDEA how much easier it'll be to write this function with strtol(), you've just saved me sooo much time writing the interpretor, thanks!
Topic archived. No new replies allowed.