如何在 C# 中将十进制字符串值转换为十六进制字节数组?

Mar*_*low 2 c# arrays hex bytearray

我有一个十进制格式的输入字符串:

var decString = "12345678"; // in hex this is 0xBC614E
Run Code Online (Sandbox Code Playgroud)

我想将其转换为固定长度的十六进制字节数组:

byte hexBytes[] // = { 0x00, 0x00, 0xBC, 0x61, 0x4E }
Run Code Online (Sandbox Code Playgroud)

我想出了一些相当复杂的方法来做到这一点,但我怀疑有一个整洁的两行!有什么想法吗?谢谢

更新:

好的,我想我可能无意中通过显示 5 个字节的示例增加了复杂性。最大值实际上是 4 个字节 (FF FF FF FF) = 4294967295。Int64 很好。

das*_*ght 5

如果您对整数的大小没有特别限制,则可以使用以下BigInteger方法进行转换:

var b = BigInteger.Parse("12345678");
var bb = b.ToByteArray();
foreach (var s in bb) {
    Console.Write("{0:x} ", s);
}
Run Code Online (Sandbox Code Playgroud)

这打印

4e 61 bc 0
Run Code Online (Sandbox Code Playgroud)

如果字节顺序很重要,您可能需要反转字节数组。

最大值实际上是 4 个字节 (FF FF FF FF) = 4294967295

你可以使用uint它 - 像这样:

uint data = uint.Parse("12345678");
byte[] bytes = new[] {
    (byte)((data>>24) & 0xFF)
,   (byte)((data>>16) & 0xFF)
,   (byte)((data>>8) & 0xFF)
,   (byte)((data>>0) & 0xFF)
};
Run Code Online (Sandbox Code Playgroud)

演示。

  • 和`Array.Reverse`,因为它似乎需要大端输出。 (2认同)