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);
}
}
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.
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).
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.
The System.Text.Encoding.UTF8
should do a trick for you.
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