📅  最后修改于: 2023-12-03 15:29:46.292000             🧑  作者: Mango
In C#, a string is an immutable sequence of characters while a byte array is a sequence of bytes. Sometimes, we may need to convert a string to a byte array to, for example, send data over a network, encrypt or decrypt data, or store text as binary data. In this tutorial, we will explore different ways of converting a string to a byte array in C#.
The System.Text.Encoding
namespace provides classes that can be used to convert strings to byte arrays and vice versa. This is accomplished using the GetBytes
method of the encoding class.
string message = "Hello World!";
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(message);
In this example, the UTF8.GetBytes
method is used to convert the string to a byte array. The resulting byte array will be in the UTF8 encoding format. Other encoding formats, such as ASCII and Unicode, can also be used.
The System.Text.ASCIIEncoding
class can also be used to convert a string to a byte array. This class provides encoding for the ASCII character set.
string message = "Hello World!";
byte[] bytes = new System.Text.ASCIIEncoding().GetBytes(message);
In this example, the ASCIIEncoding.GetBytes
method is used to convert the string to a byte array. The resulting byte array will be in the ASCII encoding format.
The System.Text.UTF8Encoding
class can also be used to convert a string to a byte array. This class provides encoding for the UTF8 character set.
string message = "Hello World!";
byte[] bytes = new System.Text.UTF8Encoding().GetBytes(message);
In this example, the UTF8Encoding.GetBytes
method is used to convert the string to a byte array. The resulting byte array will be in the UTF8 encoding format.
Another way to convert a string to a byte array in C# is to use the GetBytes
method of the Encoding.ASCII
class together with the ToCharArray
method of the String
class.
string message = "Hello World!";
char[] charArray = message.ToCharArray();
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(charArray);
In this example, the ToCharArray
method of the String
class is used to create a character array from the string. The resulting character array is then passed to the Encoding.ASCII.GetBytes
method to obtain the byte array.
We have learned different ways of converting a string to a byte array in C#. The most commonly used method is to use the GetBytes
method of the encoding class. However, depending on the encoding format required, different encoding classes can be used.