C# `{0:X2}` 在此代码示例中是什么意思?

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

What does `{0:X2}` mean in this code sample?

c#

提问by GurdeepS

In the below code sample, what does {0:X2}mean? This is from the reflection section of the MCTS Application Development Foundation book (covering dynamic code, etc.).

在下面的代码示例中,是什么{0:X2}意思?这是来自 MCTS Application Development Foundation 书籍的反射部分(涵盖动态代码等)。

foreach(Byte b in body.GetILAsBodyArray())
{
Console.Write("{0:X2}", b);
}

采纳答案by BenAlabaster

This uses the same format as String.Format(). Check out the following reference:

这使用与 String.Format() 相同的格式。查看以下参考资料:

http://msdn.microsoft.com/en-us/library/fht0f5be.aspx

http://msdn.microsoft.com/en-us/library/fht0f5be.aspx

  • X = Hexadecimal format
  • 2 = 2 characters
  • X = 十六进制格式
  • 2 = 2 个字符

回答by Niels Gjeding Olsen

Beware the length specified is not respected if the number is too large to fit the length.

请注意,如果数字太大而不适合长度,则不遵守指定的长度。

 long a = 123456789;
 Console.Write("{0:X2}", a);
 ->   75BCD15

This is especially important if you want to show negative hex numbers where all the high bits are set to 1's.

如果您想显示所有高位都设置为 1 的负十六进制数,这一点尤其重要。

 long a = -1;
 Console.Write("{0:X2}", a);
 ->  FFFFFFFFFFFFFFFF