String manipulation is a common task in C# programming. In some cases, you may need to convert a string to its equivalent byte array, such as when dealing with encryption, file I/O, or network communication. This article walks you through the process of converting a string to a byte array in C#, demonstrating the power and flexibility of C# in handling a variety of data types.
#Before we dive into the conversion process, let’s first understand strings and byte arrays in C#. In C#, a string is a sequence of characters, and a byte array (byte[]) is an array that stores bytes - raw data that a computer can process.
This is an example of string and byte array in C# -
string text = "Hello"; byte[] byteArray = { 72, 101, 108, 108, 111 };
In this example, text is the string holding "Hello" and byteArray is the byte array holding the ASCII values of the characters in "Hello".
To convert a string into a byte array in C#, we can use the GetBytes method of the Encoding class. This method encodes all characters in the specified string into a sequence of bytes.
This is an example -
using System; class Program { static void Main() { string text = "Hello"; byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(text); foreach (byte b in byteArray) { Console.WriteLine(b); } } }
In this example, we first define a string literal with the value "Hello". We then call the GetBytes method on the Encoding.UTF8 instance to convert the text into a byte array. The result is assigned to a byteArray. We then print each byte in the byteArray to the console.
72101 108 108 111
When converting a string to a byte array, remember that the result depends on the encoding used. In the above example, we used UTF8 encoding, but other encodings can also be used, such as ASCII or Unicode. Different encodings may result in different byte arrays for the same string, so always make sure to use the correct encoding for your specific use case.
Converting a string to a byte array in C# is a simple and straightforward task with the help of the GetBytes method of the Encoding class. This conversion is an essential operation in a variety of programming scenarios, including encryption, file processing, and network communications.
The above is the detailed content of Convert a string to its equivalent byte array in C#. For more information, please follow other related articles on the PHP Chinese website!