//16进制字符串转为字节数组 private byte[] hexToByteArr(string hexStr) { hexStr = hexStr.ToLower(); string[] hexStrSplit = hexStr.Split(' '); byte[] byteArr = new byte[hexStrSplit.Length / 2]; int i = 0; foreach (string hex in hexStrSplit) { byte value = Convert.ToByte(hex, 16); byteArr[i] = value; } return byteArr; }
将字节数组转换为十六进制字符串
byte[] vals = { 0x01, 0xAA, 0xB1, 0xDC, 0x10, 0xDD }; string str = BitConverter.ToString(vals); Console.WriteLine(str); str = BitConverter.ToString(vals).Replace("-", ""); Console.WriteLine(str); /*Output: 01-AA-B1-DC-10-DD 01AAB1DC10DD */
调用 .NET 5.0 中引入的 Convert.ToHexString 方法,将字节数组转换为十六进制字符串
byte[] array = { 0x64, 0x6f, 0x74, 0x63, 0x65, 0x74 }; string hexValue = Convert.ToHexString(array); Console.WriteLine(hexValue); /*Output: 646F74636574 */