C# 字符串和byte的互相转换
2010-05-15 16:45
253 查看
方法一:
//字符串转byte
string StringMessage = "How Are you?"; Console.WriteLine("{0}", StringMessage); System.Text.ASCIIEncoding ASCII = new System.Text.ASCIIEncoding(); Byte[] BytesMessage = ASCII.GetBytes(StringMessage);
//byte转字符串
Byte[] BytesMessage;
System.Text.ASCIIEncoding ASCII = new System.Text.ASCIIEncoding(); String StringMessage = ASCII.GetString( BytesMessage );
[/code]
方法二:
//字符串转UTF-8 byte
string StringMessage = "Hello World How Are you? Pi /u03C0 Yen /uFFE5"; System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding(); Byte[] BytesMessage = UTF8.GetBytes(StringMessage);
//UTF-8 byte 转字符串
Byte[] BytesMessage;
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding(); String StringMessage = UTF8.GetString( BytesMessage );
[/code]
[/code]
//直接使用BinaryFormatter 和 MemoryStream
BinaryFormatter bf = new BinaryFormatter();
byte[] bytes;
MemoryStream ms = new MemoryStream();
string orig = "喂 Hello 谢谢 Thank You";
bf.Serialize(ms, orig);
ms.Seek(0, 0);
bytes = ms.ToArray();
MessageBox.Show("Original bytes Length: " + bytes.Length.ToString());
MessageBox.Show("Original string Length: " + orig.Length.ToString());
for (int i = 0; i < bytes.Length; ++i) bytes[i] ^= 168; // pseudo encrypt
for (int i = 0; i < bytes.Length; ++i) bytes[i] ^= 168; // pseudo decrypt
BinaryFormatter bfx = new BinaryFormatter();
MemoryStream msx = new MemoryStream();
msx.Write(bytes, 0, bytes.Length);
msx.Seek(0, 0);
string sx = (string)bfx.Deserialize(msx);
MessageBox.Show("Still intact :" + sx);
MessageBox.Show("Deserialize string Length(still intact): "
+ sx.Length.ToString());
BinaryFormatter bfy = new BinaryFormatter();
MemoryStream msy = new MemoryStream();
bfy.Serialize(msy, sx);
msy.Seek(0, 0);
byte[] bytesy = msy.ToArray();
MessageBox.Show("Deserialize bytes Length(still intact): "
+ bytesy.Length.ToString());
相关文章推荐
- C#字符串与 byte数据的互相转换
- c#初学-byte数组转换为字符串
- 【转】Java中byte与16进制字符串的互相转换
- C#如何实现Object与byte[]的互相转换
- byte[]数组与十六进制字符串与字符串的互相转换(转载)
- Java中byte与16进制字符串的互相转换
- C#实现实体类与字符串互相转换的方法
- Java中byte与16进制字符串的互相转换
- C# string byte[] Base64 常用互相转换
- Java中byte与16进制字符串的互相转换 分类: Android JAVA 2015-05-26 19:07 25人阅读 评论(0) 收藏
- C#实现实体类与字符串互相转换的方法
- 图片和base64编码字符串 互相转换,图片和byte数组互相转换
- C#中字节数组(byte[])和字符串相互转换
- C#如何实现Object与byte[]的互相转换
- c# 图片 与 BASE64 字符串 互相转换。
- Java中byte与16进制字符串的互相转换
- Java中byte与16进制字符串的互相转换
- Java中byte与16进制字符串的互相转换
- Java中byte与16进制字符串的互相转换
- Java中byte与16进制字符串的互相转换