String to byte Array

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

NEXT..... Detecting arrow keys