C# ToString("X") 产生一位数的十六进制数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15233290/
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
ToString("X") produces single digit hex numbers
提问by User.1
We wrote a crude data scope.
我们写了一个粗略的数据范围。
(The freeware terminal programs we found were unable to keep up with Bluetooth speeds)
(我们发现的免费软件终端程序无法跟上蓝牙速度)
The results are okay, and we are writing them to a Comma separated file for use with a spreadsheet. It would be better to see the hex values line up in nice columns in the RichTextBox instead of the way it looks now (Screen cap appended).
结果没问题,我们将它们写入逗号分隔的文件中,以便与电子表格一起使用。最好看到十六进制值在 RichTextBox 的漂亮列中排列,而不是现在的样子(附加屏幕截图)。
This is the routine that adds the digits (e.g., numbers from 0
to FF
) to the text in the RichTextBox.
这是将数字(例如,从0
到 的数字FF
)添加到 RichTextBox 中的文本的例程。
public void Write(byte[] b)
{
if (writting)
{
for (int i = 0; i < b.Length; i++)
{
storage[sPlace++] = b[i];
pass += b[i].ToString("X") + " "; //// <<<--- Here is the problem
if (sPlace % numericUpDown1.Value == 0)
{
pass += "\r\n";
}
}
}
}
I would like a way for the instruction pass += b[i].ToString("X") + " ";
to produce a leading zero on values from 00h
to 0Fh
我想要一种方法让指令pass += b[i].ToString("X") + " ";
在从00h
到的值上产生前导零0Fh
Or, some other way to turn the value in byte b
into two alphabetic characters from 00
to FF
或者一些其他的方式把字节值b
分为两个字母字符从00
到FF
Digits on left, FF 40 0 5
Line up nice and neatly, because they are identical. As soon as we encounter any difference in data, the columns vanish and the data become extremely difficult to read with human observation.
左边的数字FF 40 0 5
,排列整齐,因为它们是相同的。一旦我们遇到任何数据差异,列就会消失,数据变得非常难以通过人类观察来阅读。
采纳答案by Oded
Use a compositeformat string:
使用复合格式字符串:
pass += b[i].ToString("X2") + " ";
The documentation on MSDN, Standard Numeric Format Stringshas examples.
MSDN 上的文档,标准数字格式字符串有示例。
回答by Yuresh Karunanayake
"X" is a format specifier. It converts a number to a string of hexadecimal digits.
“X”是格式说明符。它将数字转换为一串十六进制数字。
int _abc = 123456;
Console.WriteLine(_abc.ToString("X"));
This will give you '1E240' as output
这会给你 '1E240' 作为输出
( 1E240 is the hexadecimal value of 123456 )
(1E240 是 123456 的十六进制值)