如何将字节数组转换为字符串[duplicate]

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

This question already has an answer here: 这个问题在这里已有答案:

  • How to convert UTF-8 byte[] to string? 如何将UTF-8 byte []转换为字符串? 13 answers 13个答案

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);

你可能感兴趣的:(如何将字节数组转换为字符串[duplicate])