C 字串 位元組陣列和記憶體流間的相互轉換

2022-03-09 21:48:36 字數 2142 閱讀 5063

定義string變數為str,記憶體流變數為ms,位元陣列為bt

1.字串=>位元陣列

(1)byte bt=system.text.encoding.default.getbytes("

字串");(

2)byte bt=convert.frombase64string("

字串");

補充:

system.text.encoding.unicode.getbytes(str);

system.text.encoding.utf8.getbytes(str);

system.text.encoding.getencoding(

"gb2312

").getbytes(str); //

指定編碼方式

string str = "

中國?ss123?";

byte bytes = system.text.encoding.default.getbytes(str); //

gb2312編碼 漢字佔2個位元組、英文本母佔1個位元組 bytes長度為12

string s = system.text.encoding.default.getstring(new

byte );//

解碼後為「中」

byte bytes = ;  

string str = system.text.encoding.ascii.getstring(bytes); //

結果為:abcdef ascii碼表

常用方法:

getstring  已過載。 在派生類中重寫時,將乙個位元組序列解碼為乙個字串。

getchars 已過載。 在派生類中重寫時,將乙個位元組序列解碼為一組字元。

getbytes 已過載。 在派生類中重寫時,將一組字元編碼為乙個位元組序列。

getbytecount 已過載。 在派生類中重寫時,計算對一組字元進行編碼所產生的位元組數。

getcharcount 已過載。 在派生類中被重寫時,計算對位元組序列進行解碼所產生的字元數。

getdecoder 在派生類中重寫時,獲取乙個解碼器,該解碼器將已編碼的位元組序列轉換為字串行。

getencoder 在派生類中重寫時,獲取乙個解碼器,該解碼器將unicode字串行轉換為已編碼的位元組序列

2.位元陣列=>字串

(1)string str=system.text.encoding.default.getstring(bt);

(2)string str=convert.tobase64string(bt);

3.字串=>

(1)memorystream ms=new memorystream(system.text.encoding.default.getbytes("

字串"

));(

2)memorystream ms=new memorystream(convert.frombase64string("

字串"));

4.流=>字串

(1)string str=convert.tobase64string(ms.toarray());

(2)string str=system.text.encoding.default.getstring(ms.toarray());

5.位元陣列=>

(1)memorystream ms=new

memorystream(bt);

(2)memorystream ms=new memorystream();ms.read(bt,0,bt.lenght);

6.流=>位元陣列

(1)byte bt=ms.toarray();

(2)memorystream ms=new memorystream();ms.write(bt,0,ms.length);

c# byte陣列與image的相互轉換

C 字串 位元組陣列和記憶體流間的相互轉換

定義string變數為str,記憶體流變數為ms,位元陣列為bt 1.字串 位元陣列 1 byte bt system.text.encoding.default.getbytes 字串 2 byte bt convert.frombase64string 字串 補充 system.text.enc...

C 字串到位元組陣列,位元組陣列轉整型

int num 12345 string num1 convert.tostring 12345,16 byte bytes bitconverter.getbytes num 將int32轉換為位元組陣列 num bitconverter.toint32 bytes,0 將位元組陣列內容再轉成in...

C 字串和位元組陣列轉換

定義string變數為str,記憶體流變數為ms,位元陣列為bt 1.字串轉位元陣列 1 byte bt system.text.encoding.default.getbytes 字串 2 byte bt convert.frombase64string 字串 2.字串轉流 1 memorystr...