/// <summary> /// byte[]流轉十六進制字符串 0x34---->"34" /// </summary> /// <param name="bytes"></param> /// <returns></returns> public static string ToHexString(byte[] bytes) { char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7','8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; char[] chars = new char[bytes.Length * 2]; for (int i = 0; i < bytes.Length; i++) { int b = bytes[i];//十六進制轉化為十進制 0x34->52 chars[i * 2] = hexDigits[b >> 4]; chars[i * 2 + 1] = hexDigits[b & 0xF]; } return new string(chars); }
/// <summary> /// 字符串轉byte "34"---->52 (0x34) /// </summary> /// <param name="strAsccii"></param> /// <returns></returns> public static byte ConvertAscciiToByte(string strAsccii) { strAsccii = strAsccii.Trim(); if (strAsccii.Length > 2 || strAsccii.Length < 1) return 0x00; return byte.Parse(strAsccii, System.Globalization.NumberStyles.AllowHexSpecifier); }
測試代碼:
static void Main(string[] args) { Console.WriteLine("========================="); Console.WriteLine(" 源字符串為\"12345678\""); string nums = "12345678"; byte[] bytes1=new byte[4]; for (int n = 0; n < nums.Length/2; n++) { bytes1[n] = ConvertAscciiToByte(nums.Substring(n * 2, 2)); } Console.WriteLine("12345678字符串轉化為byte[]為 '" + bytes1[0].ToString("X") + " " + bytes1[1].ToString("X") + " " + bytes1[2].ToString("X") + " " + bytes1[3].ToString("X")+"'"); string outStr = ToHexString(bytes1); Console.WriteLine("byte[]流轉化為字符串為'"+outStr.ToString()+"'"); Console.Read(); }
輸出結果: