C# 中如何把字符串“123456”转换成Byte数组{0x12,0x34,0x56},急,在线等。。。

2025-02-01 11:00:37
推荐回答(2个)
回答1:

string str = "123456";
byte[] bytes = new byte[str.Length / 2];
for (int i = 0; i < bytes.Length; i++)
{
bytes[i] = Convert.ToByte(str.Substring(i * 2, 2), 16);
}

回答2:

byte[] bt = Regex.Matches("123456", @"\d{2}").Cast().Select(t => Convert.ToByte(t.Value.Trim())).ToArray();