Convert Strings to Byte Arrays in C#
Let's create a simple C# program to demonstrate string-to-byte array conversion using the UTF-8 encoding.
using System;
using System.Text;
class Program
{
static void Main()
{
// Input string
string inputString = "Hello, Byte Array!";
// Convert string to byte array using UTF-8 encoding
byte[] byteArray = Encoding.UTF8.GetBytes(inputString);
// Display the original string
Console.WriteLine("Original String: " + inputString);
// Display the byte array in hexadecimal format
Console.Write("Byte Array (Hex): ");
foreach (byte b in byteArray)
{
Console.Write($"{b:X2} ");
}
// Convert the byte array back to string
string decodedString = Encoding.UTF8.GetString(byteArray);
// Display the decoded string
Console.WriteLine("\nDecoded String: " + decodedString);
}
}
Output:
Original String: Hello, Byte Array!
Byte Array (Hex): 48 65 6C 6C 6F 2C 20 42 79 74 65 20 41 72 72 61 79 21
Decoded String: Hello, Byte Array!
- The program starts by defining an input string.
- It then converts the string to a byte array using the UTF-8 encoding.
- The byte array is displayed in hexadecimal format.
- Finally, the byte array is converted back to a string, and the decoded string is displayed.
Comments (0)