C#2.0中的十六进制到字节[]

时间:2011-05-31 02:27:33

标签: c# c#-2.0 bytearray

假设有一个字符串hexString = "0x12""0x45"等。如何将字符串转换为另一个字节[],如下所示。感谢。

byte[] myByte = new byte[2];
myByte[0] = 0x1;
myByte[1] = 0x2;

myByte[0] = 0x4;
myByte[1] = 0x5;

当我尝试连接下面的子字符串时,

myByte[0] = '0x' + '4'; // Show compile error. It doesn't work.

我不知道如何修复它。谢谢。 等

2 个答案:

答案 0 :(得分:1)

您是否尝试过先搜索? 试试这个:How to convert hex to a byte array?

答案 1 :(得分:1)

正在寻找这样的东西吗?

string hex = "0123456789abcdef";

string input = "0x45";
Debug.Assert(Regex.Match(input, "^0x[0-9a-f]{2}$").Success);

byte[] result = new byte[2];
result[0] = (byte)hex.IndexOf(input[2]);
result[1] = (byte)hex.IndexOf(input[3]);

// result[0] == 0x04
// result[1] == 0x05