C# Convert Byte Array to String

Conversion or change

You have an array of bytes that represent letters in ASCII in your C# program and want to convert these bytes into a string. With the ASCII.GetString method, you can pass in a byte[] array and receive a string.

Example

First, this program allocates an array of bytes: these represent characters in ASCII. Next, the ASCIIEncoding.ASCII.GetString method is used. You will need to ensure System.Text is included to compile the program.

This C# program converts a byte array to a string. It uses ASCIIEncoding.ASCII.GetString.

Program that converts byte[] to string [C#]

using System;
using System.Text;

class Program
{
    static void Main()
    {
	byte[] array =
	{
	    68,
	    111,
	    116,
	    32,
	    78,
	    101,
	    116,
	    32,
	    80,
	    101,
	    114,
	    108,
	    115
	};

	string value = ASCIIEncoding.ASCII.GetString(array);
	Console.WriteLine(value);
    }
}

Output

Dot Net Perls

Notes. The byte array does not need to contain the '\0' character to be converted to a string correctly. You can see how the space character in the example is encoded as the byte 32.

Summary

.NET Framework information

The .NET Framework provides a way for you to convert an array of bytes into a string type. With the GetString method shown here, you do not need to construct the string yourself. This site also contains information on the reverse conversion.

Convert String to Byte Array Cast Examples
.NET