C#中的Byte,String,Int,Hex之間的轉換函數。


在最近的項目中有用到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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM