This could be useful, for example, when you need to display the contents of a binary file to a user in a readable format. In this article, we will explore how to convert a byte array to a string in C# and cover two main methods for achieving this: the Encoding class and the BitConverter class.
Converting a Byte Array to a String
In C#, converting a byte array to a string is possible by using the Encoding class, which includes methods for encoding and decoding strings to and from byte arrays. The most common encoding method used to convert byte array to string is Encoding.UTF8.GetString(), here, is an illustration of how to convert a byte array to a string in C#:
using System.Text;
class Program
{
static void Main(string[] args)
{
byte[] byteArray = { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100 };
string str = Encoding.UTF8.GetString(byteArray);
Console.WriteLine(str);
}
}
Here, the ASCII values for the “Hello World” string are created as a byte array, and the string is then encoded using the UTF-8 encoding by utilizing the GetString function of the Encoding class.
Converting a Base64 Encoded String to a Byte Array
In some cases, we may need to convert a base64 encoded string to a byte array in order to perform certain operations on the data. To convert a base64-encoded string to a byte array in C#, use the Convert.FromBase64String() function. Here is an example of how to convert a base64 encoded string to a byte array in C#:
class Program
{
static void Main(string[] args)
{
string base64String = "SGVsbG8gV29ybGQ=";
byte[] byteArray = Convert.FromBase64String(base64String);
string str = System.Text.Encoding.UTF8.GetString(byteArray);
Console.WriteLine(str);
}
}
In this example, we create a string containing a base64 encoded version of the string “Hello World”. We then use the Convert.FromBase64String method to convert the string to a byte array and then used the encoding method to covert it to the string:
Conclusion
Converting between byte arrays and strings is a common task in C#, and it is important to understand how to perform these conversions. Using the Encoding class and the Convert.FromBase64String function, we have covered how to convert a byte array to a string and how to convert a base64-encoded string to a byte array.