c#中的流,字节,字符,字符串

首先要明白它们本身是由什么组成的:

流:二进制

字节:无符号整数

字符:Unicode编码字符

字符串:多个Unicode编码字符

那么在.net下它们之间如何转化呢?

一般是遵守以下规则:

流->字节数组->字符数组->字符串

下面就来具体谈谈转化的语法

流->字节数组

MemoryStream ms = new MemoryStream();

byte[] buffer = new byte[ms.Length];

ms.Read(buffer, 0, (int)ms.Length);

字节数组->流

byte[] buffer = new byte[10];

MemoryStream ms = new MemoryStream(buffer);

字节数组->字符数组

1.

byte[] buffer = new byte[10];

char[] ch = new ASCIIEncoding().GetChars(buffer);

//或者:char[] ch = Encoding.UTF8.GetChars(buffer)

2.

byte[] buffer = new byte[10];

char[] ch = new char[10];

for(int i=0; i<buffer.Length; i++)

{

    ch[i] = Convert.ToChar(buffer[i]);

}

字符数组->字节数组

1.

char[] ch = new char[10];

byte[] buffer = new ASCIIEncoding().GetBytes(ch);

//或者:byte[] buffer = Encoding.UTF8.GetBytes(ch)

2.

char[] ch = new char[10];

byte[] buffer = new byte[10];

for(int i=0; i<ch.Length; i++)

{

    buffer[i] = Convert.ToByte(ch[i]);

}

字符数组->字符串

char[] ch = new char[10];

string str = new string(ch);

 字符串->字符数组

string str = "abcde";

char[] ch=str .ToCharArray();

字节数组->字符串

byte[] buffer = new byte[10];

string str = System.Text.Encoding.UTF8.GetString(buffer);

//或者:string str = new ASCIIEncoding().GetString(buffer);

字符串->字节数组

string str = "abcde";

byte[] buffer=System.Text.Encoding.UTF8.GetBytes(str);

//或者:byte[] buffer= new ASCIIEncoding().GetBytes(str);

说明:主要就是用到了Convert类和System.Text命名空间下的类,Encoding是静态类,ASCIIEncoding是实体类,方法都是一样的!

参考文章:

c#中 uint--byte[]--char[]--string相互转换汇总

http://www.cnblogs.com/huomm/archive/2008/08/29/1279417.html

字符串如何与流相互转换?

http://topic.csdn.net/t/20041224/17/3674276.html

char[] 同 byte[] 有什么区别?

http://topic.csdn.net/t/20051102/14/4366558.html

C++中 unsigned char != byte

http://blog.csdn.net/lyskyly/archive/2008/10/02/3009582.aspx

数据流与字符串之间的转换!

http://blog.joycode.com/aspdian/archive/2004/02/29/14166.aspx

文件流转换为string(二进制转换为字符串)

http://www.cnblogs.com/riverspirit/articles/1276268.html

原文地址:https://www.cnblogs.com/ljzforever/p/1467797.html