tags:

views:

117

answers:

3

I usually use pointers in the following manner

    char *ptr = malloc( sizeof(char) * 100 );
    memset( ptr, 0, 100 ) ;
    strncpy( ptr, "cat" , 100 - 1 );

But this time instead of using "cat", I want to use it ASCII equivalent in hex.

cat = 0x63, 0x61, 0x74, 0x00

I tried

    strncpy( ptr, "0x630x61" , 100 - 1 );

But it fails as expected.

What is the correct syntax?

Do I need to put a 0x00 too? For a moment lets forget about memset, now do I need to put a 0x00? Because in "cat" notation, a null is automatically placed.

Regards

+3  A: 

\xXX is the syntax for inserting characters in hex format. so yours would be:

strncpy( ptr, "\x63\x61\x74", 100 - 1);

You don't need to put in a \x00 since having quotes automatically null-delimits the string.

Claudiu
+2  A: 
strncpy( ptr, "\x63\x61" , 100 - 1 );

0x63 is an integer hexadecimal literal; The C compiler parses it as such within code. But within a string it is interpreted as a sequence of characters 0,x,6,3. The literal for the char with value 63 hex. is '\x63', and within strings you must use this notation. "c\x63" is the literal for a zero-terminated string, irrespective of the characters within the quotes (or of the notation by which you denote them), so no, you don't need to append a trailing zero manually.

Federico Ramponi
+2  A: 

Note, you only need \ inside the " " string

char cat[4];
cat[0] = 0x63;
cat[1] = 0x61;
cat[2] = 0x74;
car[3] = 0x00;

char cat[] = "\x63\x61\x74"; // note the \0 is added for you

char cat[] = { 0x63, 0x61, 0x74, 0x00 };

Are all the same

Martin Beckett
I like the way you've shown three options, but "\0x63\0x61\0x74" is wrong. It creates an array containing the characters `0, 'x', '6', '3', 0, ...`. That's zero-length when used as a nul-terminated string.
Steve Jessop
sorry - cut and paste error!
Martin Beckett