byte[]转16进制字符串
16进制字符串转byte[]
示例代码
using System; using System.Collections.Generic; using System.Text; namespace PrototypeTest { class Program { static void Main(string[] args) { //测试数据 byte[] bytes = new byte[] {100, 200, 210, 220, 230, 240 }; string hexStr = BytesToHex(bytes); byte[] bytes1 = HexToBytes(hexStr); Console.WriteLine("测试数据:" + PrintBytes(bytes)); Console.WriteLine("byte[]转16进制:" + BytesToHex(bytes)); Console.WriteLine("16进制转byte[]:" + PrintBytes(bytes1)); Console.Read(); } static Dictionary<char, byte> hexDic = new Dictionary<char, byte>(); private static void InitHexDic() { char[] hexSymbol = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; for (byte i = 0; i < 16; i++) { hexDic.Add(hexSymbol[i], i); } } private static byte HexToByte(char hex0, char hex1) { byte b0 = hexDic[hex0]; byte b1 = hexDic[hex1]; byte result = (byte)(b0 * 16 + b1); return result; } //HexString转byte[] public static byte[] HexToBytes(string hexStr) { if (hexDic.Count <= 0) InitHexDic(); int len = hexStr.Length; if (len % 2 != 0) return null; byte[] bytes = new byte[len / 2]; for (int i = 0, j = 0; i < len; i += 2, j++) { bytes[j] = HexToByte(hexStr[i], hexStr[i + 1]); } return bytes; } //byte[]转HexString public static string BytesToHex(byte[] bytes) { int len = bytes.Length; if (len <= 0) return ""; StringBuilder sb = new StringBuilder(); for (int i = 0; i < bytes.Length; i++) sb.Append(bytes[i].ToString("x2")); return sb.ToString(); } //打印byte[] public static string PrintBytes(byte[] bytes) { int len = bytes.Length; if (len <= 0) return ""; StringBuilder sb = new StringBuilder(); for (int i = 0; i < len; i++) { if (i > 0) sb.Append(","); sb.Append(bytes[i].ToString()); } return sb.ToString(); } } }
运行测试