C# 16进制与字符串、字节数组之间的转换(二)

时间:2023-01-11 13:05:50
 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 }