Copy codeThe Code is as follows: // <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;
}
Byte array to hexadecimal string
/// <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;
}
Conversion from Chinese characters to hexadecimal
/// <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 ();
}
Hexadecimal conversion to Chinese Characters
/// <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 );
}