Search code examples
cstringhexargv

Why hex in string is not converted to hex when passed through command line argument?


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

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

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

But if I pass it to my program through command line arguments, it does 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 like in the example 1.
Why is it so? Why this method of representation does not work in case of command line arguments?
How can value in argv[1] which we know for sure is a hex string can be converted to hex number (without parsing, like done in the first example)?

Thanks for your time.


Solution

  • \x41 is an internal C representation of a byte with a value of 41 (hex). When you compile this program then in the binary it WILL be 41h (just 1 byte - not \x41). When you pass \x41 from a command line it will be treated just as a string of 4 chars hence you see what you see.