How to Convert String to Byte Array in C#?

In this tutorial, I will show you how to convert string to byte array in C# with examples.

Convert String to Byte Array in C#

The .NET Framework provides the Encoding class which is an abstract base class that provides functionalities to convert between different character encodings and bytes. The most common encodings available are:

  • Encoding.UTF8
  • Encoding.ASCII
  • Encoding.Unicode

Depending on the character encoding you want to use, you can select the appropriate method from the Encoding class.

Example

Here’s a simple example demonstrating the conversion from a string to a byte array in C#:

using System;
using System.Text;

class Program
{
    static void Main()
    {
        // Sample string
        string cities = "New York, Los Angeles, Chicago, Houston, Phoenix";

        // Convert string to byte array using UTF-8 encoding
        byte[] byteArray = Encoding.UTF8.GetBytes(cities);

        // Print byte array
        Console.WriteLine("Byte Array: ");
        foreach (byte b in byteArray)
        {
            Console.Write(b + " ");
        }

        // If needed, convert back to string
        string decodedString = Encoding.UTF8.GetString(byteArray);
        Console.WriteLine("\nDecoded String: " + decodedString);
    }
}
  1. Choice of Encoding: Different encodings will result in different byte arrays. For instance, Encoding.ASCII will only use one byte per character, but it can only represent characters in the ASCII table. On the other hand, Encoding.UTF8 can represent any character in the Unicode standard but can use more than one byte per character.
  2. Loss of Data: If you try to use an encoding that doesn’t support certain characters in your string, those characters may get replaced or lost. For example, if you use Encoding.ASCII to encode a string that contains non-ASCII characters, those characters will be replaced with a ?.
  3. Performance: If you’re doing a lot of string-to-byte conversions, consider the performance implications. For most applications, the difference in performance between different encodings is negligible. However, if performance is crucial, you might want to run some benchmarks using your data.

Once you run the code using visual studio, you will be able to see the output like below:

How to Convert String to Byte Array in C#

Converting a string to a byte array in C# is straightforward with the help of the Encoding class. In this tutorial, I have explained, how to convert a string to a byte array in C#.

You may also like: