Mohanapriya R Mohanapriya R
Updated date Jun 05, 2024
In this article, we will learn how to convert strings to binary and decode them in C# with practical examples.

How to Convert Strings to Binary in C#?

In C#, you can convert a string to its binary representation using the Encoding class. The Encoding class provides methods to convert between different character encodings. The UTF8 encoding is used for this purpose.

using System;
using System.Text;

class Program
{
    static void Main()
    {
        string inputString = "Hello, Techiehook!";
        
        byte[] binaryData = Encoding.UTF8.GetBytes(inputString);
        
        Console.WriteLine("String to Binary: ");
        foreach (byte b in binaryData)
        {
            Console.Write(Convert.ToString(b, 2).PadLeft(8, '0') + " ");
        }
    }
}

Output:

String to Binary:
01001000 01100101 01101100 01101100 01101111 00101100 00100000 01010100 01100101 01100011 01101000 01101001 01100101 01001000 01101111 01101111 01101011 00100001

How to Convert Binary to Strings in C#?

Once you have the binary representation, you might need to decode it back into a string. The Encoding class is again handy for this task. 

using System;
using System.Text;

class Program
{
    static void Main()
    {
        string inputString = "Hello, Binary!";
        
        byte[] binaryData = Encoding.UTF8.GetBytes(inputString);
        
        Console.WriteLine("String to Binary: ");
        foreach (byte b in binaryData)
        {
            Console.Write(Convert.ToString(b, 2).PadLeft(8, '0') + " ");
        }

        // Decode binary to string
        string decodedString = Encoding.UTF8.GetString(binaryData);
        Console.WriteLine("\n\nBinary to String: ");
        Console.WriteLine(decodedString);
    }
}

Output:

String to Binary:
01001000 01100101 01101100 01101100 01101111 00101100 00100000 01010100 01100101 01100011 01101000 01101001 01100101 01101000 01101111 01101111 01101011 00100001

Binary to String:
Hello, Techiehook!

Comments (0)

There are no comments. Be the first to comment!!!