How to convert byte array to string [duplicate]
-
11-12-2019 - |
Question
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).
Solution
Depending on the encoding you wish to use:
var str = System.Text.Encoding.Default.GetString(result);
OTHER TIPS
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);
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);
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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow