This post will discuss how to encode a string into a byte array in C#.

1. Using Encoding.GetBytes() method

The Encoding.GetBytes() method can be used to encode all the characters in the specified string into a byte array.

The following program creates a string extension method, ToByteArray(), which encodes the specified string into a sequence of bytes using specified ASCII encoding.

Download  Run Code

 
To decode the byte array back into a string, we can use the Encoding.GetString() method using the same ASCII encoding used for byte array conversion.

Download  Run Code

2. Using Buffer.BlockCopy() method

Here, the idea is to convert the given string into a character array and then use the Buffer.BlockCopy() method to copy all bytes from the character array to an empty byte array. The encoding used is Unicode since the ToCharArray() method returns a Unicode character array.

Download  Run Code

 
To decode the byte array back into a string, we can use the following method:

Download  Run Code

That’s all about encoding a string into a byte array in C#.