当前位置: 代码迷 >> ASP.NET >> 关于将字符串转为字节,再由字节转为字符串的有关问题
  详细解决方案

关于将字符串转为字节,再由字节转为字符串的有关问题

热度:8330   发布时间:2013-02-25 00:00:00.0
关于将字符串转为字节,再由字节转为字符串的问题
如题,比如:
将 "aaaaaaaaaa "转成了一个字节组
然后将此组连成了一个字符串保存。
如何进行反操作,
从保存的字符串得到 "aaaaaaaaaa "呢?

------解决方案--------------------------------------------------------
然后将此组连成了一个字符串保存。
-------------
不会是这样吧~

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 + ", ";
}
if (str2.Length > 0) str2 = str2.Remove(str2.Length - 1, 1);
// splits and converts the joined string to bytes
string[] strArray = str2.Split( ', ');
byte[] bytes2 = Array.ConvertAll <string, byte> (strArray, delegate(string str){ return byte.Parse(str);});
// 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);

Hope helpful!
  相关解决方案