如何將字節數組轉換爲字符串[duplicate]

本文翻譯自:How to convert byte array to string [duplicate]

This question already has an answer here: 這個問題在這裏已有答案:

I created a byte array with two strings. 我用兩個字符串創建了一個字節數組。 How do I convert a byte array to string? 如何將字節數組轉換爲字符串?

var binWriter = new BinaryWriter(new MemoryStream());
binWriter.Write("value1");
binWriter.Write("value2");
binWriter.Seek(0, SeekOrigin.Begin);

byte[] result = reader.ReadBytes((int)binWriter.BaseStream.Length);

I want to convert result to a string. 我想將result轉換爲字符串。 I could do it using BinaryReader , but I cannot use BinaryReader (it is not supported). 我可以使用BinaryReader ,但我不能使用BinaryReader (它不受支持)。


#1樓

參考:https://stackoom.com/question/mtso/如何將字節數組轉換爲字符串-duplicate


#2樓

根據您要使用的編碼:

var str = System.Text.Encoding.Default.GetString(result);

#3樓

Assuming that you are using UTF-8 encoding: 假設您使用的是UTF-8編碼:

string convert = "This is the string to be converted";

// From string to byte array
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(convert);

// From byte array to string
string s = System.Text.Encoding.UTF8.GetString(buffer, 0, buffer.Length);

#4樓

You can do it without dealing with encoding by using BlockCopy : 您可以在不使用BlockCopy處理編碼的情況下執行此操作

char[] chars = new char[bytes.Length / sizeof(char)];
System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
string str = new string(chars);

#5樓

To convert the byte[] to string[], simply use the below line. 要將byte []轉換爲string [],只需使用以下行。

byte[] fileData; // Some byte array
//Convert byte[] to string[]
var table = (Encoding.Default.GetString(
                 fileData, 
                 0, 
                 fileData.Length - 1)).Split(new string[] { "\r\n", "\r", "\n" },
                                             StringSplitOptions.None);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章