7

Is there an easy way to convert a byte array to a string so the following unit test passes? I can't find an encoding that works for all values.

  [TestMethod]
  public void TestBytToString()
  {
     byte[] bytArray = new byte[256];
     for (int i = 0; i < bytArray.Length; i++)
     {
        bytArray[i] = (byte)i;
     }
     string x = System.Text.Encoding.Default.GetString(bytArray);
     for (int i = 0; i < x.Length; i++)
     {
        int y = (int)x[i];
        Assert.AreEqual(i, y);
     }
  }
user2227596
  • 89
  • 1
  • 3
  • `Array.ConvertAll` should work for creating a `char[]`, which you can pass to a string constructor. – Ben Voigt Jul 24 '13 at 20:46
  • Avoiding the "why would you do this?" question, the only encoding this operation would be valid in would be ASCII, I think. – JerKimball Jul 24 '13 at 20:59
  • Ascii fails Expected: <128>, Actual: <63> – user2227596 Jul 24 '13 at 21:11
  • When I got your code and tested with the following , test passes `string x = new string(bytArray.Select(Convert.ToChar).ToArray());` Credit goes to [@Ricky](http://stackoverflow.com/a/9573587/1991801) – Mechanical Object Jul 24 '13 at 21:56

5 Answers5

1

The System.Text.Encoding.UTF8 should do a trick for you.

Tigran
  • 59,345
  • 8
  • 77
  • 117
1
string x = Encoding.UTF8.GetString(bytArray, 0, bytArray.Length);
Nikola Mitev
  • 4,084
  • 1
  • 17
  • 29
1
var str = System.Text.Encoding.Default.GetString(bytArray);
1Mojojojo1
  • 123
  • 1
  • 1
  • 8
0

As far as i know everthing above value 127 in byte is considered a negative number and as char can only take positive values it results with an unknown char in every encoding you take.

You might want to convert the byte array to unsigned short (ushort) and then to string...

DaMachk
  • 592
  • 3
  • 10
0

This worked:

  [TestMethod]
  public void TestBytToString()
  {
     byte[] bytArray = new byte[256];
     ushort[] usArray = new ushort[256];
     for (int i = 0; i < bytArray.Length; i++)
     {
        bytArray[i] = (byte)i;

     }

     string x = System.Text.Encoding.Default.GetString(bytArray);
     for (int i = 0; i < x.Length; i++)
     {
        int y = System.Text.Encoding.Default.GetBytes(x.Substring(i, 1))[0];
        Assert.AreEqual(i, y);
     }
  }
user2227596
  • 89
  • 1
  • 3