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);
Ruben bartelink
source share