C# program to convert a string to byte array

C# program to convert a string to byte array:

Strings can be converted to a byte array by using Encoding.ASCII.GetBytes method. Each character in a string is stored in 2 bytes. Data loss is possible sometimes.

Definition of GetBytes:

GetBytes has many overloaded methods. We are converting a string to bytes. So, we will use the below method in this example:

public virtual byte[] GetBytes (string str);

Here, str is the string with the characters to encode.

Return value:

It returns a byte array that holds the byte conversion of each character of the given string.

Exceptions:

This method might throw ArgumentNullException if the argument or the string we are passing is null. If a fallback occurs, it throws EncoderFallbackException.

C# example:

Let’s write down the example program:

using System;
using System.Text;
					
public class Program
{
	public static void Main()
	{
		String givenString = "Hello World";
		byte[] byteArr = Encoding.ASCII.GetBytes(givenString);
		
		for(int i = 0; i<byteArr.Length; i++){
			Console.WriteLine("Character: "+givenString[i]+", byte: "+byteArr[i]);
		}
	}
}

Output:

If you run this program, it will print the below output:

Character: H, byte: 72
Character: e, byte: 101
Character: l, byte: 108
Character: l, byte: 108
Character: o, byte: 111
Character:  , byte: 32
Character: W, byte: 87
Character: o, byte: 111
Character: r, byte: 114
Character: l, byte: 108
Character: d, byte: 100

Explanation:

Here,

  • givenString is the given string.
  • We are using Encoding.ASCII.GetBytes to change the string to a byte array. This value is stored in the variable byteArr.
  • The final for loop is used to print the content of the givenString string, i.e. the characters and the bytes for each character.

You can try this program with different types of strings to see the output for each.

Reference:

You might also like: