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

字節數組->字符數組

byte[] buffer = new byte[10];
char[] ch = new ASCIIEncoding().GetChars(buffer);
//或者:char[] ch = Encoding.UTF8.GetChars(buffer)
byte[] buffer = new byte[10];
char[] ch = new char[10];
for(int i=0; i<buffer.Length; i++)
{
    ch[i] = Convert.ToChar(buffer[i]);
}

 

字符數組->字節數組

char[] ch = new char[10];
byte[] buffer = new ASCIIEncoding().GetBytes(ch);
//或者:byte[] buffer = Encoding.UTF8.GetBytes(ch)
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是實體類,方法都是一樣的!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章