Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting byte array to string in C# [duplicate]

Tags:

string

c#

byte

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);
     }
  }
like image 829
user2227596 Avatar asked Jul 24 '13 20:07

user2227596


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 you convert byte into 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 we convert byte to char?

First, the byte is converted to an int via widening primitive conversion (§5.1. 2), and then the resulting int is converted to a char by narrowing primitive conversion (§5.1. 3).

What is byte array in C?

byte array in CAn unsigned char can contain a value from 0 to 255, which is the value of a byte. In this example, we are declaring 3 arrays – arr1, arr2, and arr3, arr1 is initialising with decimal elements, arr2 is initialising with octal numbers and arr3 is initialising with hexadecimal numbers.


1 Answers

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

like image 151
Tigran Avatar answered Sep 21 '22 00:09

Tigran