1. 程式人生 > >C#中的流、位元組、字元和字串

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是實體類,方法都是一樣的!