views:

65

answers:

5

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.

+4  A: 

It does work in source code because compiler(preprocessor) does the replacement. When your program work alone in the dark, there is no compiler to help to do that kind replacement.

So, if you need to parse that like compiler does - do it yourself.

BarsMonster
+1  A: 

It doesn't work because the compiler is not present in the second case to analyze the string. i.e. This only applies to string literals in your code.

AraK
+1  A: 

When using the \x approach, the compiler does the actual conversion when generating the string literals. When you pass in this via the command line, not such conversion happens as the compiler is not involved.

You will need to write some code to do the conversion.

Stephen Doyle
+1  A: 

\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.

DmitryK
A: 

Now that you've been told why it doesn't work, perhaps you'd like an idea of how to make it work. As it happens I had the same thought some years ago, and wrote some code to deal with it.

Jerry Coffin