![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
1 public class HexCode
2 {
3 /// <summary>
4 /// 从汉字转换到16进制
5 /// </summary>
6 /// <param name="s"></param>
7 /// <param name="charset">编码,如"utf-8","gb2312"</param>
8 /// <param name="fenge">是否每字符用逗号分隔</param>
9 /// <returns></returns>
10 public static string ToHex(string s, string charset, bool fenge)
11 {
12 if ((s.Length % 2) != 0)
13 {
14 s += " ";//空格
15 //throw new ArgumentException("s is not valid chinese string!");
16 }
17
18 System.Text.Encoding chs = System.Text.Encoding.GetEncoding(charset);
19
20 byte[] bytes = chs.GetBytes(s);
21
22 string str = "";
23
24 for (int i = 0; i < bytes.Length; i++)
25 {
26 str += string.Format("{0:X}", bytes[i]);
27 if (fenge && (i != bytes.Length - 1))
28 {
29 str += string.Format("{0}", ",");
30 }
31 }
32
33 return str.ToLower();
34 }
35
36 /// <summary>
37 /// 从16进制转换成汉字
38 /// </summary>
39 /// <param name="hex"></param>
40 /// <param name="charset">编码,如"utf-8","gb2312"</param>
41 /// <returns></returns>
42 public static string UnHex(string hex, string charset)
43 {
44 if (hex == null)
45 throw new ArgumentNullException("hex");
46 hex = hex.Replace(",", "");
47 hex = hex.Replace("\n", "");
48 hex = hex.Replace("\\", "");
49 hex = hex.Replace(" ", "");
50 if (hex.Length % 2 != 0)
51 {
52 hex += "20";//空格
53 //throw new ArgumentException("hex is not a valid number!", "hex");
54 }
55 // 需要将 hex 转换成 byte 数组。
56 byte[] bytes = new byte[hex.Length / 2];
57
58 for (int i = 0; i < bytes.Length; i++)
59 {
60 try
61 {
62 // 每两个字符是一个 byte。
63 bytes[i] = byte.Parse(hex.Substring(i * 2, 2),
64 System.Globalization.NumberStyles.HexNumber);
65 }
66 catch
67 {
68 // Rethrow an exception with custom message.
69 throw new ArgumentException("hex is not a valid hex number!", "hex");
70 }
71 }
72
73 System.Text.Encoding chs = System.Text.Encoding.GetEncoding(charset);
74
75
76 return chs.GetString(bytes);
77 }
78 }