Copy Code code as follows:
<summary>
string 16 binary byte array
</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), 16);
return returnbytes;
}
Byte array 16 Feed string
<summary>
Byte array 16 Feed 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;
}
Converting from Chinese to 16
<summary>
Converting from Chinese to 16
</summary>
<param name= "S" ></param>
<param name= "CharSet" > Code, such as "Utf-8", "gb2312" </param>
<param name= "Fenge" > whether each character used comma delimited </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 ();
}
Convert 16 into Chinese characters
<summary>
Convert from 16 to Chinese characters
</summary>
<param name= "Hex" ></param>
<param name= "CharSet" > Code, such as "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";//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
{
Every 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);
}