socket 發送十六進制的字符串(十六進制字符串與其他類型的轉換)(轉)


 轉自http://blog.csdn.net/jjjjj102310253/article/details/3935545

socket 發送十六進制的字符串

項目用到 socket tcp/ip 發送/接受 十六進制的字符串,因為C# socket 發送接受的都是byte[] (字節數組),現在記錄tyte[] 與各數據類型之間的轉換

注:

C#的字節數組 byte[] 存放的時間是0-255的整型數據 byte 關鍵字代表一種整型,該類型按下表所示存儲值:

可如下例所示聲明並初始化 byte 類型的變量: byte myByte = 255; 在以上聲明中,整數 255 從 int 隱式轉換為 byte。如果整數超出了 byte 的范圍,將產生編譯錯誤。

 

引子:

1.字符串轉byte[]/byte[]轉字符串

2.十六進制字符串轉byte[]/byte[]轉十六進制字符串

3.十六進制字符串與數值類型之間轉換

 4.漢字轉十六進制字符串

 

1.字符串轉byte[]/byte[]轉字符串

 

這個是經常用到的,c#中也是比較簡單的用

Encoding.UTF8.GetBytes(string data);

Encoding.UTF8.GetString(tyte[] data, 0, length);

要注意的是不同的編碼,對數據的長度甚至是內容是有影響的(一般收發兩地都使用相同的編碼)

 

2.十六進制字符串轉byte[]/byte[]轉十六進制字符串

 

十六進制字符串轉byte[]利用Convert.ToByte()方法;byte[]轉十六進制字符串利用BitConverter.ToString()或者bytes[i].ToString("X2").

[c-sharp] view plain copy

/// <summary> 

/// 16進制字符串轉字節數組 

 /// </summary> 

/// <param name="hexString"></param> 

/// <returns></returns> 

private static byte[] strToToHexByte(string hexString) 

{     

hexString = hexString.Replace(" ", "");     

if ((hexString.Length % 2) != 0)         

hexString += " ";     

byte[] returnBytes = new byte[hexString.Length / 2];     

for (int i = 0; i < returnBytes.Length; i++)         

returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2).Trim(), 16);      return returnBytes; 

}   

/// <summary> 

/// 字節數組轉16進制字符串   

/// </summary> 

/// <param name="bytes"></param> 

/// <returns></returns> 

public static string byteToHexStr(byte[] bytes) 

{     

string returnStr = "";     

if (bytes != null)     

{         

for (int i = 0; i < bytes.Length; i++)         

{             

returnStr += bytes[i].ToString("X2");         

}     

}     

return returnStr; 

 

另外,更簡單的

byte[] 轉十六進制字符串還可以利用BitConverter.ToString方法,這個更容易使用。

string str0x = BitConverter.ToString(byte[] tyt,0,length);

返回的字符串是帶“-”分離的十六進制字符串,可以去掉:

string str0x = BitConverter.ToString(byte[] tyt,0,recv).Replace("-", "");

 

BitConverter類提供基礎數據類型與字節數組相互轉換的方法。

 

3.十六進制字符串與數值類型之間轉換

十六進制字符串與數值類型之間轉換主要用到的類有 BitConverter 、Int32、 String、 Convert

Int32.Parse(),uint.Parse(),

BitConverter.GetBytes(),BitConverter.ToSingle(),

String.Format()

Convert.ToInt32(),Convert.ToByte()等方法

具體參考上篇blog

4.漢字轉十六進制字符串

[c-sharp] view plain copy

/// <summary> 

/// 從漢字轉換到16進制   

// </summary> 

/// <param name="s"></param> 

/// <param name="charset">編碼,如"utf-8","gb2312"</param> 

/// <param name="fenge">是否每字符用逗號分隔</param> 

/// <returns></returns> 

public static string ToHex(string s, string charset, bool fenge) 

{     

if ((s.Length % 2) != 0)     

{         

s += " ";//空格         

//throw new ArgumentException("s is not valid chinese string!");     

}     

System.Text.Encoding chs = System.Text.Encoding.GetEncoding(charset);     

byte[] bytes = chs.GetBytes(s);     

string str = "";     

for (int i = 0; i < bytes.Length; i++)     

{         

str += string.Format("{0:X}", bytes[i]);         

if (fenge && (i != bytes.Length - 1))         

{             

str += string.Format("{0}", ",");         

}     

}     

return str.ToLower(); 

}   

/// <summary> 

/// 從16進制轉換成漢字 

/// </summary> 

/// <param name="hex"></param> 

/// <param name="charset">編碼,如"utf-8","gb2312"</param> 

/// <returns></returns>  public static string UnHex(string hex, string charset) 

{     

if (hex == null)         

throw new ArgumentNullException("hex");     

hex = hex.Replace(",", "");     

hex = hex.Replace("/n", "");     

hex = hex.Replace("//", "");     

hex = hex.Replace(" ", "");     

if (hex.Length % 2 != 0)     

{         

hex += "20";//空格     

}     

// 需要將 hex 轉換成 byte 數組。     

byte[] bytes = new byte[hex.Length / 2];       

for (int i = 0; i < bytes.Length; i++)     

{         

try         

{             

// 每兩個字符是一個 byte。             

bytes[i] = byte.Parse(hex.Substring(i * 2, 2),             

System.Globalization.NumberStyles.HexNumber);         

}         

catch         

{             

// Rethrow an exception with custom message.             

throw new ArgumentException("hex is not a valid hex number!", "hex");         

}     

}     

System.Text.Encoding chs = System.Text.Encoding.GetEncoding(charset);     

return chs.GetString(bytes); 

 


免責聲明!

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



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