1. 程式人生 > >C# 16進制與字符串、字節數組之間的轉換(二)

C# 16進制與字符串、字節數組之間的轉換(二)

bool sub ber con tostring mat cep 字節數組 log

 1 /// <summary>   
 2 /// 字符串轉16進制字節數組   
 3 /// </summary>   
 4 /// <param name="hexString"></param>   
 5 /// <returns></returns>   
 6 private static byte[] strToToHexByte(string hexString)   
 7 {   
 8     hexString = hexString.Replace(" ", "");   
 9     if ((hexString.Length % 2
) != 0) 10 hexString += " "; 11 byte[] returnBytes = new byte[hexString.Length / 2]; 12 for (int i = 0; i < returnBytes.Length; i++) 13 returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16); 14 return returnBytes; 15 } 16 17 /// <summary>
18 /// 字節數組轉16進制字符串 19 /// </summary> 20 /// <param name="bytes"></param> 21 /// <returns></returns> 22 public static string byteToHexStr(byte[] bytes) 23 { 24 string returnStr = ""; 25 if (bytes != null) 26 { 27 for (int i = 0; i < bytes.Length; i++)
28 { 29 returnStr += bytes[i].ToString("X2"); 30 } 31 } 32 return returnStr; 33 } 34 35 /// <summary> 36 /// 從漢字轉換到16進制 37 /// </summary> 38 /// <param name="s"></param> 39 /// <param name="charset">編碼,如"utf-8","gb2312"</param> 40 /// <param name="fenge">是否每字符用逗號分隔</param> 41 /// <returns></returns> 42 public static string ToHex(string s, string charset, bool fenge) 43 { 44 if ((s.Length % 2) != 0) 45 { 46 s += " ";//空格 47 //throw new ArgumentException("s is not valid chinese string!"); 48 } 49 System.Text.Encoding chs = System.Text.Encoding.GetEncoding(charset); 50 byte[] bytes = chs.GetBytes(s); 51 string str = ""; 52 for (int i = 0; i < bytes.Length; i++) 53 { 54 str += string.Format("{0:X}", bytes[i]); 55 if (fenge && (i != bytes.Length - 1)) 56 { 57 str += string.Format("{0}", ","); 58 } 59 } 60 return str.ToLower(); 61 } 62 63 ///<summary> 64 /// 從16進制轉換成漢字 65 /// </summary> 66 /// <param name="hex"></param> 67 /// <param name="charset">編碼,如"utf-8","gb2312"</param> 68 /// <returns></returns> 69 public static string UnHex(string hex, string charset) 70 { 71 if (hex == null) 72 throw new ArgumentNullException("hex"); 73 hex = hex.Replace(",", ""); 74 hex = hex.Replace("\n", ""); 75 hex = hex.Replace("\\", ""); 76 hex = hex.Replace(" ", ""); 77 if (hex.Length % 2 != 0) 78 { 79 hex += "20";//空格 80 } 81 // 需要將 hex 轉換成 byte 數組。 82 byte[] bytes = new byte[hex.Length / 2]; 83 for (int i = 0; i < bytes.Length; i++) 84 { 85 try 86 { 87 // 每兩個字符是一個 byte。 88 bytes[i] = byte.Parse(hex.Substring(i * 2, 2), 89 System.Globalization.NumberStyles.HexNumber); 90 } 91 catch 92 { 93 // Rethrow an exception with custom message. 94 throw new ArgumentException("hex is not a valid hex number!", "hex"); 95 } 96 } 97 System.Text.Encoding chs = System.Text.Encoding.GetEncoding(charset); 98 return chs.GetString(bytes); 99 }

C# 16進制與字符串、字節數組之間的轉換(二)