Mohanapriya R Mohanapriya R
Updated date May 05, 2024
In this article, we will discover converting byte arrays to strings in C#. Learn the basics, explore encoding, and follow a step-by-step program for seamless byte array conversion.

How to Convert Byte Arrays to Strings in C#?

C# provides the Encoding class, which offers methods for converting byte arrays to strings and vice versa. One of the commonly used encodings is UTF-8. 

Program:

using System;
using System.Text;

class Program
{
    static void Main()
    {
        // Creating a sample byte array
        byte[] byteArray = { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100 };

        // Converting byte array to string using UTF-8 encoding
        string resultString = Encoding.UTF8.GetString(byteArray);

        // Displaying the result
        Console.WriteLine("Byte Array to String Conversion Result:");
        Console.WriteLine(resultString);
    }
}

Output:

Byte Array to String Conversion Result:
Hello World

In this program, we create a byte array representing the ASCII values of the characters "Hello World." We then use the GetString method of the Encoding class with UTF-8 encoding to convert the byte array to a string. Finally, we display the result, which is the string "Hello World."

Comments (0)

There are no comments. Be the first to comment!!!