How to Convert string to binary in C#
By FoxLearn 2/10/2025 7:21:59 AM 5.97K
In a Windows Forms application in C#, you can create a simple user interface to input a string and display its binary representation.
How to convert string to binary in C#?
Drag and drop the textbox, label and button controls from your Visual Studio toolbox to your winform, then layout your UI as shown below.
Next, Create the StringToBinary method allow you to convert text to binary as the following c# code.
For example, convert string to binary c#
// c# convert string to binary public string StringToBinary(string data) { // string to binary data c# StringBuilder sb = new StringBuilder(); foreach (char c in data.ToCharArray()) sb.Append(Convert.ToString(c, 2).PadLeft(8, '0')); return sb.ToString(); }
Finally, Add an event handler for the button click event where you perform the conversion.
// c# convert string to binary sequence private void btnConvert_Click(object sender, EventArgs e) { // c# string to binary txtOutput.Text = StringToBinary(txtInput.Text); }
Press F5 to build and run your project, this code will convert the string entered in the txtInput
to binary sequence and display it in the txtOutput
when the btnConvert
is clicked.