859

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

LHM
  • 721
  • 12
  • 31
Oksana
  • 13,442
  • 10
  • 53
  • 89
  • 5
    You already have the strings, so you can't actually be doing exactly this - what exactly *are* you doing? – harold Jul 25 '12 at 16:45
  • 2
    @harold from a «value1/2» strings I guess it's just an example. – Hi-Angel Mar 30 '15 at 11:59
  • The OP did not accept the answer that assumes UTF-8 encoding, but did accept a different answer, suggesting that it is not safe to assume UTF-8 encoding. – Raedwald Nov 23 '17 at 20:30
  • 1
    You can just do `new String(result)` – Seraf Sep 10 '18 at 16:58
  • If you don't know the encoding you can use `using (StreamReader sr = new StreamReader(memoryStream, detectEncodingFromByteOrderMarks: true))` where `memoryStream` has been initialized with the `byte[]` – Patrick from NDepend team Oct 04 '22 at 12:30

4 Answers4

1381

Depending on the encoding you wish to use:

var str = System.Text.Encoding.Default.GetString(result);
eulerfx
  • 36,769
  • 7
  • 61
  • 83
  • 32
    You should also use the encoding class to write the string to a byte array. – Servy Jul 25 '12 at 16:43
  • 8
    That actually gives a funny result, because he wrote the string with the BinaryWriter.Write(string) overload, which first saves the length of the string. – harold Jul 25 '12 at 16:44
  • Note that this will sanitize the bytes that go into the string to conform to the encoding. If you want to test a bad sequence of bytes for that encoding, use the BlockCopy method below by HforHisham. – Nick Westgate Sep 02 '14 at 05:34
  • 13
    Also it's important to be aware that `System.Text.Encoding.Default` is the *system's current ANSI code page* - the results of this will vary depending on how the operating system is configured. If you know what encoding the string really is you should use that one instead. – Wolfgang Nov 05 '15 at 15:18
  • 5
    This is wrong. From the code in the question, the encoding is UTF8, the default for BinaryWriter. – Tom Blodget Feb 13 '16 at 02:19
  • 1
    See https://stackoverflow.com/questions/10611455/what-is-character-encoding-and-why-should-i-bother-with-it – Raedwald Nov 23 '17 at 20:37
  • 1
    If I use this then it returns diamonds in the result. Where as this works: `Convert.ToBase64String` - why is that? – variable Jan 05 '22 at 11:16
404

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);
ba0708
  • 10,180
  • 13
  • 67
  • 99
  • 41
    This answer saves readers the inevitable google search for the other conversion direction. – Zoomzoom Jul 25 '18 at 13:08
  • 4
    This answer is more accurate, because of encoding specification and another side conversion. – pcdro Sep 20 '18 at 20:08
  • 12
    What merit does `System.Text.Encoding.UTF8.GetString(buffer, 0, buffer.Length);` bring compared to `System.Text.Encoding.UTF8.GetString(buffer);`? – Wouter Vanherck Nov 06 '18 at 14:24
  • 4
    @WouterVanherck Judging by the [reference source](https://referencesource.microsoft.com/#mscorlib/system/text/encoding.cs,1483), not much. – JAD Mar 01 '19 at 11:55
  • 3
    Also work for me `BitConverter.ToString(byteArray))` https://learn.microsoft.com/en-us/dotnet/api/system.bitconverter.tostring?view=net-5.0 – Arsen Tagaev Jul 04 '21 at 06:15
  • If I use this then it returns chinese characters in the result. Where as this works: `Convert.ToBase64String` - why is that? – variable Jan 05 '22 at 11:18
  • 1
    @WouterVanherck If you're using a fixed buffer, versus allocating the buffer on the fly based on BytesToRead, then you'll have an issue when converting to string if the BytesToRead is less than the buffer size. All the zeros in the buffer will be converted to '\0' in your string. Using the GetString(buffer, index, length) lets you avoid needing to potentially strip '\0's from your output string and the headache of determining whether they were even supposed to be part of the output at all. – iheanyi Mar 02 '22 at 23:18
30

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);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
HforHisham
  • 1,914
  • 1
  • 22
  • 34
  • This didn't work for me. I got an error on the length (not dividing gives the length I needed). After getting the correct length I got an argumentException trying to construct the string. – David Silva Smith Oct 20 '13 at 16:20
  • 1
    This only works if your string was encoded with UTF16 which is [c# string's default internal encoding scheme](http://stackoverflow.com/questions/14942092/why-does-net-uses-the-utf16-encoding-for-string-but-uses-utf8-as-default-for). If, say, the byte array was encoded simply with ASCII chars from the original string (assuming it can be), after the BlockCopy, each char will be squeezed with two such ASCII characters, which is clearly wrong. – KFL Aug 14 '14 at 06:41
  • 12
    On the flipside, if you're trying to create a damaged string for testing, this is exactly the way to do it. Thanks! – Nick Westgate Sep 02 '14 at 05:28
  • I don't think you need to worry about encoding if you only want to convert to string and then back, see http://stackoverflow.com/questions/472906/converting-a-string-to-byte-array – mcmillab Sep 15 '14 at 06:00
  • 3
    I think if you use `Math.Ceiling` on `bytes.Length / sizeof(char)` then it will always work correctly. – Lukasz Jun 09 '15 at 11:48
12

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);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mansoor Ali
  • 153
  • 1
  • 2