C#中字符数组,字节数组和string之间的转化
转自:http://blog.csdn.net/wangxiaoqin00007/article/details/17675419
NDC(NetworkDiskClient)的界面和后台程序之间用Socket通信,发送命令。 环境:界面:C# winform 后台:Vc++,消息通知 网络通信,C#是通过网络字节流进行传输的,传输内容是有报文头的Protobuf。Net消息。报文头是struct结构体,先转化成byte[],protobuf消息就先转换为内存流,再stream.ToArray[]转化为字节数组,就可以由Socket传输。 字符串string和内存流MemoryStream及比特数组byte[]互转比较 定义string变量为str,内存流变量为ms,比特数组为bt 1.字符串转比特数组 (1)byte[] bt=System.Text.Encoding.Default.GetBytes("字符串"); (2)byte[] bt=Convert.FromBase64String("字符串"); 2.字符串转流 (1)MemoryStream ms=new MemoryStream(System.Text.Encoding.Default.GetBytes("字符串")); (2)MemoryStream ms=new MemoryStream(Convert.FromBase64String("字符串")); 3.流转比特数组 (1)byte[] bt=ms.ToArray(); (2)MemoryStream ms=new MemoryStream();ms.Write(bt,0,ms.Length); 4.流转字符串 (1)string str=Convert.ToBase64String(ms.ToArray()); (2)string str=System.Text.Encoding.Default.GetString(ms.ToArray()); 5.比特数组转字符串 (1)string str=System.Text.Encoding.Default.GetString(bt); (2)string str=Convert.ToBase64String(bt); 6.比特数组转流 (1)MemoryStream ms=new MemoryStream(bt); (2)MemoryStream ms=new MemoryStream();ms.Read(bt,0,bt.Lenght);