问题
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. I could do it using BinaryReader
, but I cannot use BinaryReader
(it is 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);
来源:https://stackoverflow.com/questions/11654562/how-to-convert-byte-array-to-string