How to assign char * value using hexadecimal notation?

I usually use pointers as follows

  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 its ASCII equivalent in hexadecimal.

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

I tried

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

But he fails as expected.

What is the correct syntax?

Do I also need to put 0x00? For a moment, forget about memset , now I need to put 0x00? Because in the cat notation, zero is automatically placed.

Hi

+5
source share
3 answers

\xXX is the syntax for inserting characters in hexadecimal format. so your will be:

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

You do not need to insert \x00 , because with the help of quotes, it automatically nullifies the line.

+11
source

Please note: you only need \ in 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 }; 

All the same

+5
source
 strncpy( ptr, "\x63\x61" , 100 - 1 ); 

0x63 is an integer hexadecimal literal; The C compiler parses it as such in code. But inside the string, it is interpreted as a sequence of characters 0,x,6,3 . Literal for char with a value of 63 hex. '\x63' , and inside the lines you should use this notation. "c\x63" is a literal for a zero-terminated string, regardless of the characters inside the quotation marks (or the notation by which you label them), so no, you do not need to manually add the trailing zero.

+2
source

Source: https://habr.com/ru/post/1303730/


All Articles