c#中的流,位元組,字元,字串

來源:互聯網
上載者:User

首先要明白它們本身是由什麼組成的:

流:二進位

位元組:不帶正負號的整數

字元: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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.