How to Convert Strings to Binary Encode in C#
The below C# program converts a user provided string into its binary representation:
using System;
using System.Text;
class Program
{
static void Main()
{
Console.Write("Enter a string: ");
string input = Console.ReadLine();
// Convert string to binary
string binaryRepresentation = StringToBinary(input);
// Display the result
Console.WriteLine($"Binary representation: {binaryRepresentation}");
}
static string StringToBinary(string input)
{
byte[] bytes = Encoding.ASCII.GetBytes(input);
StringBuilder binary = new StringBuilder();
foreach (byte b in bytes)
{
binary.Append(Convert.ToString(b, 2).PadLeft(8, '0'));
}
return binary.ToString();
}
}
The above program starts with prompting the user to enter a string. Once the user enters the string, the StringToBinary
method gets the user input and converts it into a binary representation. It uses the Encoding.ASCII.GetBytes
method to get the ASCII values of each character in the string. Then, it converts each ASCII value to an 8-bit binary representation. Lastly, the binary representation is displayed to the user.
Output:
Enter a string:
Hello
Binary representation: 0100100001100101011011000110110001101111
Enter a string:
Binary
Binary representation: 0100001001101001001100001101001101101001
Comments (0)