How to Convert binary to text in C#

By FoxLearn 7/19/2024 2:09:44 AM   6.91K
Convert binary to text in C# Windows Forms Application by entering binary in TextBox, then pressing the convert button and displaying the result in TextBox control.

How to Convert binary to text in C#

To convert binary to string in c#, i will create a form allow me to enter binary then convert to text.

Drag and drop the TextBox, Label and Button from your Visual Studio toolbox to your winform, then layout your UI as shown below.

convert binary to string in c#

Next, Create the BinaryToString method allow you to convert binary to text in c# as the following code.

public string BinaryToString(string data)
{
    List<byte> bytes = new List<byte>();
    for (int i = 0; i < data.Length; i += 8)
        bytes.Add(Convert.ToByte(data.Substring(i, 8), 2));
    return Encoding.ASCII.GetString(bytes.ToArray());
}

Finally, Add code to handle the Convert button click event.

private void btnConvert_Click(object sender, EventArgs e)
{
    txtOutput.Text = BinaryToString(txtInput.Text);
}

In this example, txtInput is a TextBox where the user enters the binary data, and txtOutput is another TextBox where the converted text will be displayed. The btnConvert_Click event handler is called when the user clicks a button to initiate the conversion process.

The BinaryToString method converts the binary string to text by parsing it in chunks of 8 bits (1 byte) and converting each chunk to its ASCII character equivalent. Finally, it returns the resulting text.

Press F5 to build and run your project, then you can enter the binary code and convert binary to string in c#. In other words, you have created a binary to string converter in c# winforms.