Convert a byte array to a string in C#
This post will discuss how to convert a byte array to a string in C#.
1. Using Encoding.GetString() method
To decode all bytes in the byte array into a string, use the Encoding.GetString() method. Several decoding schemes are available in Encoding class – UTF8, Unicode, UTF32, ASCII, etc.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
using System; using System.Text; public class Example { public static void Main() { byte[] bytes = Encoding.Default.GetBytes("ABC123"); Console.WriteLine("Byte Array is: " + String.Join(" ", bytes)); string str = Encoding.Default.GetString(bytes); Console.WriteLine("The String is: " + str); } } /* Output: Byte Array is: 65 66 67 49 50 51 The String is: ABC123 */ |
2. Using Convert.ToBase64String() method
To decode the bytes encoded with base-64 digits, use the Convert.ToBase64String() method. This is demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
using System; public class Example { public static void Main() { byte[] bytes = Convert.FromBase64String("QUJDMTIz"); Console.WriteLine("Byte Array is: " + String.Join(" ", bytes)); string str = Convert.ToBase64String(bytes); Console.WriteLine("The String is: " + str); } } /* Output: Byte Array is: 65 66 67 49 50 51 The String is: QUJDMTIz */ |
3. Using MemoryStream Class
Here, the idea is to create the byte stream from a specified byte array. Then read all characters from the byte stream and return the stream as a string.
The following code example shows how to implement this. The solution automatically tries to determine the encoding used using the byte order mark (BOM) in the byte stream. If not found, UTF-8 encoding is assumed.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
using System; using System.Text; using System.IO; public class Example { static string BytesToString(byte[] bytes) { using (MemoryStream stream = new MemoryStream(bytes)) { using (StreamReader streamReader = new StreamReader(stream)) { return streamReader.ReadToEnd(); } } } public static void Main() { byte[] bytes = Encoding.ASCII.GetBytes("ABC123"); Console.WriteLine("Byte Array is: " + String.Join(" ", bytes)); string str = BytesToString(bytes); Console.WriteLine("The String is: " + str); } } /* Output: Byte Array is: 65 66 67 49 50 51 The String is: ABC123 */ |
That’s all about converting a byte array to a string in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)