Convert String to / from Byte Array examples | C# Examples

This tutorial explains about following things in C#

  • How to parse String to Byte Array
  • How to convert Byte Array to String in C Sharp?
  • Convert String array to byte array

Convert String to Byte Array in C# with examples

Multiple ways to convert String to Byte Array

The first way, use Encoding.ASCII.GetBytes

First, use the System.Text namespace into your code

byte[] bytes = Encoding.ASCII.GetBytes("Hello");

Here is an example

using System;
using System.Text; 
public class Program {
  public static void Main() {
      byte[] bytes = Encoding.ASCII.GetBytes("Hello");
      string str = Encoding.ASCII.GetString(bytes);
      Console.WriteLine(str);

  }
}

This approach uses default encoding such as ASCII, But not UTF-16, It uses 7 bit.

Another way using System.Text.Encoding.UTF8,

using System;
using System.Text; 
public class Program {
  public static void Main() {
        // Convert  string to  byte array
      ReadOnlySpan<byte> bytes1 = System.Text.Encoding.UTF8.GetBytes("hello1");

      // Convert byte array to string
      string str = Encoding.ASCII.GetString(bytes1);//hello1

      Console.WriteLine(str); 

  }
}

The third way, In C# 11 version, uses UTF-8 string literals syntax.

Append u8 to a string converted into a byte array.

using System;
using System.Text; 
public class Program {
  public static void Main() {  
    // Convert  string to  byte array
    ReadOnlySpan<byte> bytes2 = "hello3"u8;
    // Convert byte array to string
    string str = Encoding.ASCII.GetString(bytes2); //hello3

    Console.WriteLine(str);

  }
}

The fourth way, assign the string variable to a byte array, It casts and converts to the array.

string str = "welcome"; 
byte[] array = str;

Byte Array to String in C# with examples

Multiple ways to convert byte array to String

One way using Encoding.ASCII.GetString method

string str = Encoding.ASCII.GetString(bytes); // hello

It supports ASCII, but not UTF-8 or UTF-16 encoding.

The second way, use System.Text.Encoding.UTF8.GetString

Takes byte array and return string

using System;
using System.Text; 
public class Program {
  public static void Main() {
      byte[] bytes = Encoding.ASCII.GetBytes("Hello");
      
      ReadOnlySpan<byte> bytes1 = System.Text.Encoding.UTF8.GetBytes("hello1");
      string str = System.Text.Encoding.UTF8.GetString(bytes1);

      Console.WriteLine(str); // hello1

  }
}

Convert String array to/ from byte array