C# 字符串和byte的互相转换

方法一:
//字符串转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 );
方法二:
//字符串转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 );

//直接使用BinaryFormatterMemoryStream

 

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()); 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值