字符串16进制ASCII码的转换
1///<;字符串转16进制格式,不够⾃动前⾯补零>
2///假设⽂本框⾥⾯填写的是:01 02 03 04 05 06
3/// Str获取的是01 02 03 04 05 06 是字符串
4///需要将01转为0x01,02转为0x02
5///⾸先默认把⽂本框每隔两个字符作为⼀个16进制数
6///假设⽂本框中是010*********(偶数个数据),则01,02,03,04,05,06分别作为16进制
7///如果⽂本框中的字符个数是奇数个1115268,则默认先把前⾯每隔两个作为⼀个16进制数,最后⼀个数前⾯补零0x11,0x15,0x26,0x08 8///</summary>
9///<param name="hexString"></param>
10///<returns>返回字符数组</returns>
11public static byte[] strToToHexByte(String hexString) {
12int i;
13 hexString = hexString.Replace("", "");//清除空格
14if ((hexString.Length % 2) != 0)//奇数个
15 {
16byte[] returnBytes = new byte[(hexString.Length + 1) / 2];
17try {
18for (i = 0; i < (hexString.Length - 1) / 2; i++) {
19 returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
20 }
21 returnBytes[returnBytes.Length - 1] = Convert.ToByte(hexString.Substring(hexString.Length - 1, 1).PadLeft(2, '0'), 16);
22 } catch {
23 MessageBox.Show("含有⾮16进制字符", "提⽰");
24return null;
25 }
26return returnBytes;
27 } else {
28byte[] returnBytes = new byte[(hexString.Length) / 2];
29try {
30for (i = 0; i < returnBytes.Length; i++) {
31 returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
32 }
33 } catch {
34 MessageBox.Show("含有⾮16进制字符", "提⽰");
35return null;
36 }
37return returnBytes;
38 }
39 }
40///<summary>
41///将字符串s通过ASCII码转换为16进制字符串
42///</summary>
43///<param name="s"></param>
44///<param name="encode"></param>
45///<returns>⼗六进制字符串</returns>
46private static string result;//string转16进制的结果
47public static string stringToHexString(string s, Encoding encode) {
48byte[] b = encode.GetBytes(s);//按照指定编码将string编程字节数组
49 result = string.Empty;
50for (int i = 0; i < b.Length; i++)//逐字节变为16进制字符
51 {
52 result += Convert.ToString(b[i], 16);
53 }
54return result;
55 }
56
57///<summary>
58///将⼀条⼗六进制字符串转换为ASCII
59///</summary>
60///<param name="hexstring">⼀条⼗六进制字符串</param>
61///<returns>返回⼀条ASCII码</returns>数组格式字符串转数组
62public static string hexStringToASCII(string hexstring) {
63byte[] bt = hexStringToBinary(hexstring);
64string lin = "";
65for (int i = 0; i < bt.Length; i++) {
66 lin = lin + bt[i] + "";
67 }
68string[] ss = lin.Trim().Split(new char[] { '' });
69char[] c = new char[ss.Length];
70int a;
71for (int i = 0; i < c.Length; i++) {
72 a = Convert.ToInt32(ss[i]);
73 c[i] = Convert.ToChar(a);
74 }
75string b = new string(c);
76return b;
77 }
78///<summary>
79/// 16进制字符串转换为⼆进制数组
80///</summary>
81///<param name="hexstring">⽤空格切割字符串</param> 82///<returns>返回⼀个⼆进制字符串</returns>
83public static byte[] hexStringToBinary(string hexstring) { 84string[] tmpary = hexstring.Trim().Split('');
85byte[] buff = new byte[tmpary.Length];
86for (int i = 0; i < buff.Length; i++) {
87 buff[i] = Convert.ToByte(tmpary[i], 16);
88 }
89return buff;
90 }
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论