【发布时间】:2020-03-01 15:39:26
【问题描述】:
我想将 int 转换为 hex 4 字节。
我用这个:
int a = 50;
a.ToString("X8");
这返回“00000032”。
但我想返回“0x00, 0x00, 0x00, 0x32”。
感谢您的帮助。
【问题讨论】:
我想将 int 转换为 hex 4 字节。
我用这个:
int a = 50;
a.ToString("X8");
这返回“00000032”。
但我想返回“0x00, 0x00, 0x00, 0x32”。
感谢您的帮助。
【问题讨论】:
这是一个你需要非常小心“字节序”的地方;在最简单的情况下,最好的办法是使用移位操作,即
static void Main()
{
static string ByteHex(int value) => (value & 0xFF).ToString("X2");
int a = 50;
Console.WriteLine("0x" + ByteHex(a >> 24));
Console.WriteLine("0x" + ByteHex(a >> 16));
Console.WriteLine("0x" + ByteHex(a >> 8));
Console.WriteLine("0x" + ByteHex(a));
}
在更细微的情况下,有一个新的BinaryPrimitives 类型是你的朋友:
int a = 50;
Span<byte> span = stackalloc byte[4];
BinaryPrimitives.WriteInt32BigEndian(span, a);
// now access span[0] - span[3]
这通常比 BitConverter 更可取,其中 a: 分配繁重,而 b: 是笨拙的重新字节序(你需要打开 BitConverter.IsLittleEndian)
【讨论】:
这应该可以完成工作:
int a = 50;
string result = string.Join(", ", BitConverter.GetBytes(a).Reverse().Select(b => "0x" + b.ToString("X2")));
Console.WriteLine(result);
【讨论】: