How convert byte array to string [duplicate]

2019-01-01 01:45发布

问题:

This question already has an answer here:

  • How to convert UTF-8 byte[] to string? 13 answers

I created a byte array with two strings. How do I convert a byte array to strings?

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 strings. I can do it using BinaryReader. But I can not use BinaryReader (it does not supported).

回答1:

Depending on the encoding you wish to use:

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


回答2:

Assuming that you are using UTF-8 encoding:

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


回答3:

You can do it without dealing with encoding by using BlockCopy:

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


回答4:

To convert the byte[] to string[], simply use the below line.

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


回答5:

An alternative option is:

string convert = \"This is the string to be converted\";
convert.CopyTo(0, buffer, 0, convert.length);

See String.CopyTo (MSDN).