C# 将 int 转换为带前导零的十六进制
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15919979/
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
Convert int to hex with leading zeros
提问by user2264990
How to convert int (4 bytes) to hex ("XX XX XX XX
") without cycles?
如何在XX XX XX XX
没有循环的情况下将 int(4 个字节)转换为十六进制(“ ”)?
for example:
例如:
i=13 hex="00 00 00 0D"
i.ToString("X")
returns "D"
, but I need a 4-bytes hex value.
i.ToString("X")
返回"D"
,但我需要一个 4 字节的十六进制值。
采纳答案by CodesInChaos
You can specify the minimum number of digits by appending the number of hex digits you want to the X
format string. Since two hex digits correspond to one byte, your example with 4 bytes needs 8 hex digits. i.e. use i.ToString("X8")
.
您可以通过将所需的十六进制位数附加到X
格式字符串来指定最小位数。由于两个十六进制数字对应一个字节,因此您的 4 个字节示例需要 8 个十六进制数字。即使用i.ToString("X8")
。
If you want lower case letters, use x
instead of X
. For example 13.ToString("x8")
maps to 0000000d
.
如果您想要小写字母,请使用x
代替X
。例如13.ToString("x8")
映射到0000000d
.
回答by KF2
try this:
尝试这个:
int innum = 123;
string Hex = innum .ToString("X"); // gives you hex "7B"
string Hex = innum .ToString("X8"); // gives you hex 8 digit "0000007B"