Search code examples
c#binaryasciitypeconverter

How can I display extended ASCII characters from binary number in C#?


I am trying to convert binary numbers to ASCII characters. While I am displaying the binary numbers in the textbox or label, I am getting symbol "?". I want to get all ASCII characters include the extended ones with the original symbols.

I just couldn't get the extended ones. I am searching for two days and I couldn't figured out.

Can somebody help me ?

Edit : My code is this and when I am trying to extended ASCII's , I just get in the label "?"

Simple explanation :

String binary= "11001100";
label1.text = BinaryToString(binary);


public static string BinaryToString(string data)
    {
        List<Byte> byteList = new List<Byte>();

        for (int i = 0; i < data.Length; i += 8)
        {
            byteList.Add(Convert.ToByte(data.Substring(i, 8), 2));
        }

        return Encoding.ASCII.GetString(byteList.ToArray());
    }

Solution

  • Encoding.ASCII specifically says it only works on the lowest 128 characters. What you probably really want for arbitrary conversion of single bytes is code page 437, based on a related answer.

    private static Encoding cp437 = Encoding.GetEncoding(437);
    public static string BinaryToString(string data) {
        List<Byte> byteList = new List<Byte>();
    
        for (int i = 0; i < data.Length; i += 8) {
            byteList.Add(Convert.ToByte(data.Substring(i, 8), 2));
        }
    
        return cp437.GetString(byteList.ToArray());
    }