C# - 将 Int 转换为 Hex 4 字节

C# - Convert Int to Hex 4 Bytes

我想将 int 转换为 hex 4 字节。

我用这个:

int a = 50;
a.ToString("X8");

这个return“00000032”。

但我想 return "0x00, 0x00, 0x00, 0x32".

感谢您的帮助。

这应该可以完成工作:

int a = 50;

string result = string.Join(", ", BitConverter.GetBytes(a).Reverse().Select(b => "0x" + b.ToString("X2")));

Console.WriteLine(result);

这是一个你需要非常小心的地方"endianness";在大多数简单的情况下,最好的选择是使用移位操作,即

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