How to convert text to binary code in C#

1 Answer

0 votes
using System;

class Program
{
    static string TextToBin(string txt) {
        string bin = string.Empty;

        foreach (char ch in txt) {
            // Convert character to ASCII value
            int ascii = (int)ch;

            // Convert ASCII value to binary string
            string binary = Convert.ToString(ascii, 2);

            // Pad binary string to ensure it is 8 bits long
            binary = binary.PadLeft(8, '0');

            // Append binary string to result
            bin += binary + " ";
        }

        return bin.Trim(); // Remove trailing space
    }

    static void Main(string[] args)
    {
        string str = "CSharp";
        
        string binaryResult = TextToBin(str);

        Console.WriteLine(binaryResult);
    }
}


/*
run:

01000011 01010011 01101000 01100001 01110010 01110000

*/

 



answered Apr 13 by avibootz
...