How to convert byte array to string in C#?

CsharpServer Side ProgrammingProgramming

Complete Python Prime Pack

9 Courses     2 eBooks

Artificial Intelligence & Machine Learning Prime Pack

6 Courses     1 eBooks

Java Prime Pack

9 Courses     2 eBooks

In .Net, every string has a character set and encoding. A character encoding tells the computer how to interpret raw zeroes and ones into real characters. It usually does this by pairing numbers with characters. Actually, it is the process of transforming a set of Unicode characters into a sequence of bytes.

We can use Encoding.GetString Method (Byte[]) to decodes all the bytes in the specified byte array into a string. Several other decoding schemes are also available in Encoding class such as UTF8, Unicode, UTF32, ASCII etc. The Encoding class is available as part of System.Text namespace.

string result = Encoding.Default.GetString(byteArray);

Example

Live Demo

using System;
using System.Text;
namespace DemoApplication {
public class Program {
static void Main(string[] args) {
byte[] byteArray = Encoding.Default.GetBytes("Hello World");
Console.WriteLine($"Byte Array is: {string.Join(" ", byteArray)}"); string str = Encoding.Default.GetString(byteArray); Console.WriteLine($"String is: {str}");
}
}
}

Output

The output of the above code is

Byte Array is: 72 101 108 108 111 32 87 111 114 108 100
String is: Hello World

It is important to note that we should use the same encoding for both directions. For example, if the byte array is encoded with ASCII and we are trying to get the string using UTF32, we won’t get the desired string.

Example

Live Demo

using System;
using System.Text;
namespace DemoApplication {
public class Program {
static void Main(string[] args) {
byte[] byteArray = Encoding.ASCII.GetBytes("Hello World");
Console.WriteLine($"Byte Array is: {string.Join(" ", byteArray)}"); string str = Encoding.UTF32.GetString(byteArray); Console.WriteLine($"String is: {str}");
}
Byte Array is: 72 101 108 108 111 32 87 111 114 108 100
String is: ???