C# 构建十六进制表示法字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/284093/
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-08-03 21:35:50  来源:igfitidea点击:

C# Build hexadecimal notation string

c#stringhex

提问by humcfc

How do I build an escape sequence string in hexadecimal notation.

如何以十六进制表示法构建转义序列字符串。

Example:

例子:

string s = "\x1A"; // this will create the hex-value 1A or dec-value 26

I want to be able to build strings with hex-values between 00 to FF like this (in this example 1B)

我希望能够像这样构建十六进制值在 00 到 FF 之间的字符串(在本例中为 1B)

string s = "\x" + "1B"; // Unrecognized escape sequence

Maybe there's another way of making hexadecimal strings...

也许还有另一种制作十六进制字符串的方法......

采纳答案by FlySwat

You don't store hexadecimal values in strings.

您不在字符串中存储十六进制值。

You can, but it would just be that, a string, and would have to be cast to an integer or a byte to actually read its value.

您可以,但它只是一个字符串,并且必须转换为整数或字节才能实际读取其值。

You can assign a hexadecimal value as a literal to an int or a byte though:

您可以将十六进制值作为文字分配给 int 或字节:

Byte value = 0x0FF;
int value = 0x1B;

So, its easily possible to pass an hexadecimal literal into your string:

因此,很容易将十六进制文字传递到您的字符串中:

string foo = String.Format("{0} hex test", 0x0BB);

Which would create this string "126 hex test".

这将创建此字符串“126 hex test”。

But I don't think that's what you wanted?

但我不认为那是你想要的吗?

回答by Nicolas Repiquet

There's an '\u' escape code for hexadecimal 16 bitsunicode character codes.

十六进制16 位unicode 字符代码有一个 '\u' 转义码。

Console.WriteLine( "Look, I'm so happy : \u263A" );

回答by Jon Skeet

Please try to avoid the \xescape sequence. It's difficult to read because where it stops depends on the data. For instance, how much difference is there at a glance between these two strings?

请尽量避免\x转义序列。它很难阅读,因为它在哪里停止取决于数据。比如,这两个字符串乍一看有多大区别?

"\x9Good compiler"
"\x9Bad compiler"

In the former, the "\x9" is tab - the escape sequence stops there because 'G' is not a valid hex character. In the second string, "\x9Bad" is all an escape sequence, leaving you with some random Unicode character and " compiler".

在前者中,“\x9”是制表符 - 转义序列在那里停止,因为 'G' 不是有效的十六进制字符。在第二个字符串中,“\x9Bad”都是一个转义序列,留下一些随机的 Unicode 字符和“编译器”。

I suggest you use the \u escape sequence instead:

我建议您改用 \u 转义序列:

"\u0009Good compiler"
"\u0009Bad compiler"

(Of course for tab you'd use \tbut I hope you see what I mean...)

(当然对于你会使用的标签,\t但我希望你明白我的意思......)

This is somewhat aside from the original question of course, but that's been answered already :)

这当然与最初的问题有点不同,但这已经得到了回答:)