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).
There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.
One method is to create a string variable and then append the byte value to the string variable with the help of + operator. This will directly convert the byte value to a string and add it in the string variable.
For text or character data, we use new String(bytes, StandardCharsets. UTF_8) to convert the byte[] to a String directly. However, for cases that byte[] is holding the binary data like the image or other non-text data, the best practice is to convert the byte[] into a Base64 encoded string.
Depending on the encoding you wish to use:
var str = System.Text.Encoding.Default.GetString(result);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With