I can do this:
int main(int argc, char** argv) {
unsigned char cTest = 0xff;
return 0;
}
But what’s the right way to get a hexadecimal number into the program via the command line?
unsigned char cTest = argv[1];
doesn’t do the trick. That produces a initialization makes integer from pointer without a cast warning.
As the type of
mainindicates, arguments from the command line are strings and will require conversion to different representations.Converting a single hexadecimal command-line argument to decimal looks like
Example usage:
Using
strtoland changing the final argument from 16 to 0 as inmakes the program accept decimal, hexadecimal (indicated by leading
0x, and octal (indicated by leading0) values:Using the bash command shell, take advantage of ANSI-C Quoting to have the shell perform the conversion, and then your program just prints the values from the command line.
Bash supports many formats of the form
$'...', but$'\xHH'appears to be the closest match to your question. For example:Maybe you pack the values from the command line into a string and print it.
In action:
All of the above is reinventing wheels that bash and the operating system already provide for you.
The
echoprogram prints its command-line arguments on the standard output, which you can think of as aforloop over the arguments and aprintffor each.If you have another program that performs the decoding for you, use Command Substitution that replaces a command surrounded by backticks or
$()with its output. See examples below, which again useechoas a placeholder.