During serial communication, hexadecimal conversion, String Conversion, and byte array conversion are often used.
/// <Summary>
/// Convert string to hexadecimal byte array
/// </Summary>
/// <Param name = "hexstring"> </param>
/// <Returns> </returns>
Private Static byte [] strtohexbyte (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), 16 );
Return returnbytes;
}
/// <Summary>
/// Convert byte array to hexadecimal string
/// </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;
}
/// <Summary>
/// Convert Chinese characters to hexadecimal
/// </Summary>
/// <Param name = "S"> </param>
/// <Param name = "charset"> encoding, such as "UTF-8" and "gb2312" </param>
/// <Param name = "Fenge"> whether to separate each character with commas </param>
/// <Returns> </returns>
Public static string tohex (string S, string charset, bool Fenge)
{
If (S. Length % 2 )! = 0)
{
S + = ""; // Space
// 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>
/// Convert from hexadecimal to Chinese Characters
/// </Summary>
/// <Param name = "hex"> </param>
/// <Param name = "charset"> encoding, such as "UTF-8" and "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"; // Space
}
// You Need to Convert hex to a byte array.
Byte [] bytes = new byte [Hex. Length/2];
For (INT I = 0; I <bytes. length; I ++)
{
Try
{
// Each two characters is a 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 );
}