Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign a value to a char* using hex notation?

Tags:

c

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

like image 759
Andrew-Dufresne Avatar asked Mar 10 '10 21:03

Andrew-Dufresne


1 Answers

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

like image 53
Martin Beckett Avatar answered Oct 03 '22 01:10

Martin Beckett