C++ "\x" 如何在字符串中工作?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10057258/
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
How does "\x" work in a String?
提问by Nosrettap
I'm writing a C/C++ program that involves putting a hex representation of a number into a string and I'm confused as to how \x
works. I've seen examples where people have written things such as "\xb2". In this case, how does the program know if you want the hex of b followed by the number 2 or if you want the hex of b2? Additionally, when it stores this into memeory does it save the "\x" characters or does it just save the hex representation?
我正在编写一个 C/C++ 程序,该程序涉及将一个数字的十六进制表示形式放入一个字符串中,但我对如何\x
工作感到困惑。我看过一些例子,人们写了诸如“\xb2”之类的东西。在这种情况下,程序如何知道您想要 b 的十六进制后跟数字 2 还是想要 b2 的十六进制?此外,当它将此存储到内存中时,它是保存“\x”字符还是只保存十六进制表示?
回答by Oliver Charlesworth
From the C99 standard (6.4.4.4):
来自 C99 标准 (6.4.4.4):
Each octal or hexadecimal escape sequence is the longest sequence of characters that can constitute the escape sequence.
每个八进制或十六进制转义序列是可以构成转义序列的最长字符序列。
回答by Kendall Frey
As an example, the string "123\x45"
is stored in hex as 31 32 33 45
.
例如,字符串"123\x45"
以十六进制存储为31 32 33 45
.
As per Oli's answer, the longest valid value after the '\x' is used.
根据 Oli 的回答,使用 '\x' 之后的最长有效值。
The '\x' is not stored. Any escape sequence does not store the characters you see on the screen, it stores the actual character specified. For example, '\n' is actually stored as a linefeed character, 0x0A.
'\x' 不存储。任何转义序列都不会存储您在屏幕上看到的字符,而是存储指定的实际字符。例如,'\n' 实际上存储为换行符 0x0A。
回答by Robert Groves
When you use the escape sequence \x inside a string the data following the \x is actually stored in it's binary representation.
当您在字符串中使用转义序列 \x 时, \x 后面的数据实际上存储在它的二进制表示中。
So the string "ABC" is equivalent to the string "\x414243"
所以字符串“ABC”等价于字符串“\x414243”
If you want to emit hexadecimal values in display-character form, you'll want to use the %x or %X format specifier character:
如果要以显示字符形式发出十六进制值,则需要使用 %x 或 %X 格式说明符字符:
printf("%X%X%X", 'A', 'B', 'C'); // emits "414243"
See Section 1.2.6and Section 1.2.7of the C Library Reference Guide
Hope that explanation helps.
希望这个解释有帮助。
回答by Andreas Hagen
The translation is done at compile-time so that every string you manually enter into the source code with \x
and such ends up being the character it represents in the binary. If you want to do this at run-time you will need to invoke a parse function like strtol()
using base 16 passing the string containing the hex and cast it to a char.
翻译是在编译时完成的,因此您手动输入到源代码中的每个字符串都会成为\x
它在二进制文件中表示的字符。如果您想在运行时执行此操作,您将需要调用一个解析函数,例如strtol()
使用 base 16 传递包含十六进制的字符串并将其转换为字符。