Why doesn't the hex in the string convert to hex when passed through a command line argument?

I understand that hexadecimal numbers can be put in a string using \x . For example, 0x41 0x42 can be placed in a string as "\x41\x42" .

 char * ptr = "\x41\x42" ; printf( "%s\n" , ptr ) // AB 

\x discarded, and 41 is considered by the compiler as hex.

But if I pass it into my program via command line arguments, this will not work.

  // test.c main( int argc , char * argv[] ) { printf( "%s\n" , argv[1] ) ; } 

$ gcc -o prog test.c
$. / prog "\ x41 \ x42"
\ X41 \ x42
$ .prog \ x41 \ x42
\ X41 \ x42

What I expected was AB as in example 1.
Why is this so? Why does this presentation method not work with command line arguments?
How can the value in argv[1] , which we know for sure, be a hexadecimal string, can be converted to a hexadecimal number (without parsing, as is done in the first example)?

Thank you for your time.

+4
source share
6 answers

\ x41 is the internal representation of the C byte with a value of 41 (hex). When you compile this program, then in the binary file it will be 41h (only 1 byte - not \ x41). When you pass \ x41 from the command line, it will be treated as a 4-character string, so you see what you see.

+2
source

It works in the source code because the compiler (preprocessor) performs the replacement. When your program runs alone in the dark, there is no compiler to help make such a replacement.

So, if you need to parse how the compiler does it, do it yourself.

+5
source

It will work if you call your program as follows:

 ./prog $'\x41\x41\x41' 

which coincides with

 ./prog "AAA" 
+4
source

This does not work because the compiler is not present in the second case to parse the string. that is, this only applies to string literals in your code.

+1
source

When using the \ x approach, the compiler performs the actual conversion when generating string literals. When you pass this through the command line, such a conversion does not occur because the compiler is not involved.

You will need to write code to convert.

+1
source

Now that you have been told why this does not work, you might like how to make it work. Be that as it may, I thought a few years ago and wrote some code to deal with it.

0
source

All Articles