日期:2014-05-18  浏览次数:20614 次

如何把byte数组转换成16进制的字符传,然后在把16进制的字符传转换回byte数组哦?
如何把byte数组转换成16进制的字符传,然后在把16进制的字符传转换回byte数组哦?麻烦给一个代码示例,谢谢``

------解决方案--------------------
try ->

void StringBytesConverter3()
{
const char SEPARATOR = ' ';
string str1 = "hello world ";
// specifies the Encoding method
Encoding encoding;
encoding = System.Text.Encoding.UTF8;
// also as
// encoding = System.Text.Encoding.Unicode;
// encoding = System.Text.Encoding.GetEncoding( "GB2312 ");
// more encodings ...

// string > bytes
byte[] bytes = encoding.GetBytes(str1);
// joins the bytes
string str2 = " ";
foreach(byte b in bytes)
{
str2 += b.ToString( "X ") + SEPARATOR.ToString();
}
if(str2.Length > 0) str2 = str2.Remove(str2.Length - 1, 1);
// splits and converts the joined string to bytes
string[] strArray = str2.Split(new char[] { SEPARATOR });
byte[] bytes2 = Array.ConvertAll <string, byte> (strArray, delegate(string str) { return byte.Parse(str, System.Globalization.NumberStyles.AllowHexSpecifier); });
// bytes > string
string str3 = encoding.GetString(bytes2);
// out
Response.Write( "original string: " + str1);
Response.Write( " <br/> ");
Response.Write( "joined bytes: " + str2);
Response.Write( " <br/> ");
Response.Write( "recovered string: " + str3);
}