C语言 如何使用十六进制表示法为 char* 赋值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2420780/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:48:29  来源:igfitidea点击:

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

c

提问by Andrew-Dufresne

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.

但这一次,我想使用与 ASCII 等效的十六进制形式,而不是使用“cat”。

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

猫 = 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.

我也需要输入 0x00 吗?让我们暂时忘记memset,现在我需要输入 0x00 吗?因为在“cat”符号中,会自动放置一个空值。

Regards

问候

回答by Claudiu

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

\xXX是以十六进制格式插入字符的语法。所以你的将是:

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

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

您不需要输入 a\x00因为引号会自动对字符串进行空分隔。

回答by Martin Beckett

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 
strncpy( ptr, "\x63\x61" , 100 - 1 );
is added for you char cat[] = { 0x63, 0x61, 0x74, 0x00 };

Are all the same

都一样

回答by Federico A. Ramponi

##代码##

0x63is 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 charwith value 63 hex. is '\x63', and within strings you must use this notation. "c\x63"is the literal for a zero-terminatedstring, 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.

0x63是一个整数十六进制文字;C 编译器在代码中解析它。但在一个字符串中,它被解释为一个字符序列0,x,6,3char值为 63 十六进制的文字。is '\x63',并且在字符串中您必须使用此表示法。 "c\x63"零终止字符串的文字,与引号内的字符(或表示它们的符号)无关,因此不,您不需要手动附加尾随零。