Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert byte array to string [duplicate]

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

like image 858
Oksana Avatar asked Jul 25 '12 16:07

Oksana


People also ask

How do you convert a byte array into a string?

There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.

Can we convert byte to string?

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.

Can you store a byte array as a string?

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.


2 Answers

Depending on the encoding you wish to use:

var str = System.Text.Encoding.Default.GetString(result); 
like image 77
eulerfx Avatar answered Oct 07 '22 01:10

eulerfx


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); 
like image 33
ba0708 Avatar answered Oct 07 '22 03:10

ba0708