在最近的项目中有用到PLC与上位机通信的指令转换,用了各种方法,很是头疼,在网上搜集了和自己试着写了一下转换函数,分享给有需要的朋友。

  1         /// <summary> Convert a string of hex digits (ex: E4 CA B2) to a byte array. </summary>
  2         /// <param name="s"> The string containing the hex digits (with or without spaces). </param>
  3         /// <returns> Returns an array of bytes. </returns>
  4         public byte[] HexStringToByteArray(string s)
  5         {
  6             s = s.Replace(" ", "");
  7             byte[] buffer = new byte[s.Length / 2];
  8             for (int i = 0; i < s.Length; i += 2)
  9             {
 10                 buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
 11             }
 12 
 13             return buffer;
 14         }
 15 
 16         /// <summary> Converts an array of bytes into a formatted string of hex digits (ex: E4 CA B2)</summary>
 17         /// <param name="data"> The array of bytes to be translated into a string of hex digits. </param>
 18         /// <returns> Returns a well formatted string of hex digits with spacing. </returns>
 19         public string ByteArrayToHexString(byte[] data)
 20         {
 21             StringBuilder sb = new StringBuilder(data.Length * 3);
 22             foreach (byte b in data)
 23             {
 24                 sb.Append(Convert.ToString(b, 16).PadLeft(2, '0').PadRight(3, ' '));
 25             }
 26 
 27             return sb.ToString().ToUpper();
 28         }
 29 
 30         /// <summary>
 31         /// 将一条十六进制字符串转换为ASCII
 32         /// </summary>
 33         /// <param name="hexstring">一条十六进制字符串</param>
 34         /// <returns>返回一条ASCII码</returns>
 35         public static string HexStringToASCII(string hexstring)
 36         {
 37             byte[] bt = HexStringToBinary(hexstring);
 38             string lin = "";
 39             for (int i = 0; i < bt.Length; i++)
 40             {
 41                 lin = lin + bt[i] + " ";
 42             }
 43 
 44 
 45             string[] ss = lin.Trim().Split(new char[] { ' ' });
 46             char[] c = new char[ss.Length];
 47             int a;
 48             for (int i = 0; i < c.Length; i++)
 49             {
 50                 a = Convert.ToInt32(ss[i]);
 51                 c[i] = Convert.ToChar(a);
 52             }
 53 
 54             string b = new string(c);
 55             return b;
 56         }
 57 
 58 
 59         /**/
 60         /// <summary>
 61         /// 16进制字符串转换为二进制数组
 62         /// </summary>
 63         /// <param name="hexstring">用空格切割字符串</param>
 64         /// <returns>返回一个二进制字符串</returns>
 65         public static byte[] HexStringToBinary(string hexstring)
 66         {
 67 
 68             string[] tmpary = hexstring.Trim().Split(' ');
 69             byte[] buff = new byte[tmpary.Length];
 70             for (int i = 0; i < buff.Length; i++)
 71             {
 72                 buff[i] = Convert.ToByte(tmpary[i], 16);
 73             }
 74             return buff;
 75         }
 76 
 77 
 78         /// <summary>
 79         /// 将byte型转换为字符串
 80         /// </summary>
 81         /// <param name="arrInput">byte型数组</param>
 82         /// <returns>目标字符串</returns>
 83         private string ByteArrayToString(byte[] arrInput)
 84         {
 85             int i;
 86             StringBuilder sOutput = new StringBuilder(arrInput.Length);
 87             for (i = 0; i < arrInput.Length; i++)
 88             {
 89                 sOutput.Append(arrInput[i].ToString("X2"));
 90             }
 91             //将此实例的值转换为System.String
 92             return sOutput.ToString();
 93         }
 94 
 95 
 96 
 97         /// <summary>
 98         /// 对接收到的数据进行解包(将接收到的byte型数组解包为Unicode字符串)
 99         /// </summary>
100         /// <param name="recbytes">byte型数组</param>
101         /// <returns>Unicode编码的字符串</returns>
102         public string disPackage(byte[] recbytes)
103         {
104             string temp = "";
105             foreach (byte b in recbytes)
106                 temp += b.ToString("X2") + " ";//ToString("X2") 为C#中的字符串格式控制符
107             return temp;
108         }
109 
110         /**
111     * int转byte[]
112     * 该方法将一个int类型的数据转换为byte[]形式,因为int为32bit,而byte为8bit所以在进行类型转换时,知会获取低8位,
113     * 丢弃高24位。通过位移的方式,将32bit的数据转换成4个8bit的数据。注意 &0xff,在这当中,&0xff简单理解为一把剪刀,
114     * 将想要获取的8位数据截取出来。
115     * @param i 一个int数字
116     * @return byte[]
117     */
118         public static byte[] int2ByteArray(int i)
119         {
120             byte[] result = new byte[4];
121             result[0] = (byte)((i >> 24) & 0xFF);
122             result[1] = (byte)((i >> 16) & 0xFF);
123             result[2] = (byte)((i >> 8) & 0xFF);
124             result[3] = (byte)(i & 0xFF);
125             return result;
126         }
127         /**
128          * byte[]转int
129          * 利用int2ByteArray方法,将一个int转为byte[],但在解析时,需要将数据还原。同样使用移位的方式,将适当的位数进行还原,
130          * 0xFF为16进制的数据,所以在其后每加上一位,就相当于二进制加上4位。同时,使用|=号拼接数据,将其还原成最终的int数据
131          * @param bytes byte类型数组
132          * @return int数字
133          */
134         public static int bytes2Int(byte[] bytes)
135         {
136             int num = bytes[3] & 0xFF;
137             num |= ((bytes[2] << 8) & 0xFF00);
138             num |= ((bytes[1] << 16) & 0xFF0000);
139             num |= ((bytes[0] << 24) & 0xFF0000);
140             return num;
141         }
142 
143         public static string Int2String(int str)
144         {
145             string S = Convert.ToString(str);
146             return S;
147         }
148 
149         public static int String2Int(string str)
150         {
151             int a;
152             int.TryParse(str, out a);
153             int a1 = Convert.ToInt32(str);
154             return a1;
155         }
156 
157 
158         /*将int转为低字节在后,高字节在前的byte数组
159 b[0] = 11111111(0xff) & 01100001
160 b[1] = 11111111(0xff) & 00000000
161 b[2] = 11111111(0xff) & 00000000
162 b[3] = 11111111(0xff) & 00000000
163 */
164         public byte[] IntToByteArray2(int value)
165         {
166             byte[] src = new byte[4];
167             src[0] = (byte)((value >> 24) & 0xFF);
168             src[1] = (byte)((value >> 16) & 0xFF);
169             src[2] = (byte)((value >> 8) & 0xFF);
170             src[3] = (byte)(value & 0xFF);
171             return src;
172         }
173         //将高字节在前转为int,低字节在后的byte数组(与IntToByteArray2想对应)
174         public int ByteArrayToInt2(byte[] bArr)
175         {
176             if (bArr.Length != 4)
177             {
178                 return -1;
179             }
180             return (int)((((bArr[0] & 0xff) << 24)
181                        | ((bArr[1] & 0xff) << 16)
182                        | ((bArr[2] & 0xff) << 8)
183    | ((bArr[3] & 0xff) << 0)));
184         }
185 
186         public static string StringToHexArray(string input)
187         {
188             char[] values = input.ToCharArray();
189             StringBuilder sb = new StringBuilder(input.Length * 3);
190             foreach (char letter in values)
191             {
192                 // Get the integral value of the character.
193                 int value = Convert.ToInt32(letter);
194                 // Convert the decimal value to a hexadecimal value in string form.
195                 string hexOutput = String.Format("{0:X}", value);
196                 sb.Append(Convert.ToString(value, 16).PadLeft(2, '0').PadRight(3, ' '));
197             }
198 
199             return sb.ToString().ToUpper();
200 
201             #endregion
202 
203         }

在这个过程中有参考网上大神的代码:

和谐:https://www.cnblogs.com/wxbug/p/6991445.html

王思明:https://www.cnblogs.com/maanshancss/p/4074524.html

 

posted on 2018-07-27 14:54  april007  阅读(17241)  评论(1编辑  收藏  举报