首先要明白它們本身是由什麼組成的:
流:二進位
位元組:不帶正負號的整數
字元: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