Convert Strings to Binary in C#
In computing, data is stored in binary format, using combinations of 0s and 1s. Each character in a string can be represented by a unique sequence of bits.
using System;
class StringToBinaryConverter
{
static void Main()
{
Console.Write("Enter a string: ");
string inputString = Console.ReadLine();
// Convert the string to binary
string binaryRepresentation = StringToBinary(inputString);
// Display the result
Console.WriteLine($"Binary representation: {binaryRepresentation}");
}
static string StringToBinary(string input)
{
// Convert each character to binary and concatenate
string binaryResult = string.Join(" ",
input.Select(c => Convert.ToString(c, 2).PadLeft(8, '0')));
return binaryResult;
}
}
Output:
Enter a string: Hello
Binary representation: 01001000 01100101 01101100 01101100 01101111
Comments (0)