如下字串與位元組陣列互換的例子:
byte msg = encoding.unicode.getbytes(textbox1.text);
this.label1.text = encoding.unicode.getstring(msg);
system.text.encoding 類似乎沒有可用的建構函式,但我們可以找到幾個預設的 encoding,即 encoding.default(獲取系統的當前 ansi **頁的編碼)、encoding.ascii(獲取 7 位 ascii 字符集的編碼)、encoding.unicode(獲取採用 little-endian 位元組順序的 unicode 格式的編碼)、encoding.utf7(獲取 utf-7 格式的編碼)、encoding.utf8(獲取 utf-8 格式的編碼) 等。這裡主要說說 encoding.default 和 encoding.unicode 用於轉換的區別。
在字串轉換到位元組陣列的過程中,encoding.default 會將每個單位元組字元,如半形英文,而把每個雙位元組字元,如漢字。而 encoding.unicode 則會將它們都轉換成兩個位元組。我們可以通過下列簡單的了解一下轉換的方法,以及使用 encoding.default 和 encodeing.unicode 的區別:
private void teststringbytes()
foreach (byte b in b2)
this.textbox1.text = "";
}
執行結果如下,不說詳述,相信大家已經明白了。
b1.length = 6
67 35 211 239 209 212
b2.length = 8
67 0 35 0 237 139 0 138
將c#位元組陣列轉換成字串,使用 encoding 類的 string getstring(byte) 或 string getstring(byte, int, int) 方法,具體使用何種 encoding 還是由編碼決定。在 teststringbytes() 函式中新增如下語句作為例項:
byte bs = ;
string ss = system.text.encoding.ascii.getstring(bs);
執行結果為:the string is: abcdef
C 字串和位元組陣列轉換
定義string變數為str,記憶體流變數為ms,位元陣列為bt 1.字串轉位元陣列 1 byte bt system.text.encoding.default.getbytes 字串 2 byte bt convert.frombase64string 字串 2.字串轉流 1 memorystr...
C 字串到位元組陣列,位元組陣列轉整型
int num 12345 string num1 convert.tostring 12345,16 byte bytes bitconverter.getbytes num 將int32轉換為位元組陣列 num bitconverter.toint32 bytes,0 將位元組陣列內容再轉成in...
字串與位元組陣列的轉換
字串與位元組陣列的轉換 string str helloworld byte data str.getbytes for int x 0 x data.length x data x 32 system.out.print datd x system.out.println new string d...