Getting the hexadecimal number into the program through the command line

I can do it:

int main(int argc, char** argv) { unsigned char cTest = 0xff; return 0; } 

But what is the correct way to get the hexadecimal number in the program through the command line?

unsigned char cTest = argv[1];

doesn't do the trick. This creates initialization by making an integer from the pointer without a throw warning.

+7
c strtol base-conversion
source share
6 answers
 #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { printf("%ld\n", strtol(argv[1], NULL, 16)); return 0; } 

Usage example:

  $ ./hex ff
 255 
+7
source share

I think some people arriving here may just search:

 $ ./prog `python -c 'print "\x41\x42\x43"'` $ ./prog `perl -e 'print "\x41\x42\x43"'` $ ./prog `ruby -e 'print "\x41\x42\x43"'` 
+11
source share

You can use strtoul , which will go through the characters in the string and convert them, taking into account radix (16 in this context), which you pass: -

 char *terminatedAt; if (argc != 2) return 1; unsigned long value = strtoul( argv[1], &terminatedAt, 16); if (*terminatedAt != '\0') return 2; if (value > UCHAR_MAX) return 3; unsigned char byte = (unsigned char)value; printf( "value entered was: %d", byte); 

As shown in other examples, there are shorter ways, but none of them allows you to cleanly check for error handling (what happens if someone passes FFF and you only unsiged char to put it in

eg. with sscanf :

 int val; sscanf(argv[1], &val) printf("%d\n", val); 
+7
source share
 unsigned char cTest = argv[1]; 

incorrect because argv[1] is of type char * . If argv[1] contains something like "0xff" and you want to assign an integer value corresponding to this unsigned char , the easiest way would probably be to use strtoul() to convert it to unsigned long , and then check whether the converted value is less than or equal to UCHAR_MAX . If so, you can simply assign cTest .

strtoul() The third parameter is the base, which can be 0 to indicate parsing a number in C style (octal and hexadecimal literals are allowed). If you want to allow base 16, pass this as the third argument to strtoul() . If you want to allow any base (so you can parse 0xff , 0377 , 255 , etc.), use 0.

UCHAR_MAX defined in <limits.h> .

+4
source share

The traditional way to do this is in C - scanf () . This is exactly the inverse of printf (), reading this format from a file (or terminal) and into a list of variables, rather than writing them to it.

In your case, you should use sscanf , since you already have it in the string, and not in the stream.

+1
source share

atoi , atol , strtoi , strtoi

everything in stdlib.h

-3
source share

All Articles