用前导零将int转换为十六进制
问题描述:
如何在不使用循环的情况下将int(4个字节)转换为十六进制("XX XX XX XX
")?
How to convert int (4 bytes) to hex ("XX XX XX XX
") without cycles?
例如:
i=13 hex="00 00 00 0D"
i.ToString("X")
返回"D"
,但是我需要一个4字节的十六进制值.
i.ToString("X")
returns "D"
, but I need a 4-bytes hex value.
答
您可以通过将所需的十六进制数字附加到X
格式字符串中来指定最小位数.由于两个十六进制数字对应一个字节,因此具有4个字节的示例需要8个十六进制数字.即使用i.ToString("X8")
.
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
而不是X
.例如,13.ToString("x8")
映射到0000000d
.
If you want lower case letters, use x
instead of X
. For example 13.ToString("x8")
maps to 0000000d
.