String to byte Array

c# character set and encoding

In C#, you can convert a string to a byte array using the Encoding class, which provides methods for encoding and decoding character data. The most commonly used encoding is UTF-8, but you can choose other encodings like UTF-16, ASCII, etc., depending on your requirements. Here's how you can convert a string to a byte array in C#:

Using UTF-8 encoding (default)

using System; using System.Text; class Program { static void Main() { string text = "Hello, World!"; byte[] byteArray = Encoding.UTF8.GetBytes(text); Console.WriteLine("Original string: " + text); Console.WriteLine("Byte array:"); foreach (byte b in byteArray) { Console.Write(b + " "); } } }
//Output: Original string: Hello, World! Byte array: 72 101 108 108 111 44 32 87 111 114 108 100 33

Using ASCII encoding

using System; using System.Text; class Program { static void Main() { string text = "Hello, World!"; byte[] byteArray = Encoding.ASCII.GetBytes(text); Console.WriteLine("Original string: " + text); Console.WriteLine("Byte array:"); foreach (byte b in byteArray) { Console.Write(b + " "); } } }
//Output: Original string: Hello, World! Byte array: 72 101 108 108 111 44 32 87 111 114 108 100 33

Using UTF-16 encoding

using System; using System.Text; class Program { static void Main() { string text = "Hello, World!"; byte[] byteArray = Encoding.Unicode.GetBytes(text); // UTF-16 encoding Console.WriteLine("Original string: " + text); Console.WriteLine("Byte array:"); foreach (byte b in byteArray) { Console.Write(b + " "); } } }
//Output: Original string: Hello, World! Byte array: 72 0 101 0 108 0 108 0 111 0 44 0 32 0 87 0 111 0 114 0 108 0 100 0 33 0

Remember that the byte array represents the encoded form of the string using the chosen encoding. If you need to convert the byte array back to the original string, you can use the corresponding Encoding class method, such as Encoding.UTF8.GetString(byteArray) for UTF-8 encoding.

Conclusion

c# string to bytearray

Keep in mind that different encodings have different byte representations for characters, so choose the appropriate encoding based on your specific use case and the data you are dealing with. UTF-8 is generally recommended for general use due to its compatibility with various characters and languages.