C#字符串与ASII16(HEX)进制相互转换

 

ContractedBlock.gif ExpandedBlockStart.gif Code
 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 * 22),
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 }

转载于:https://www.cnblogs.com/zhangpengshou/archive/2008/08/07/1263325.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值