5

I am trying to take ASCII from textBox1 and display the text in binary in textBox2. A simple ASCII to Binary converter.

        private void button1_Click(object sender, EventArgs e)
    {
        byte[] inVAR = System.Text.Encoding.ASCII.GetBytes(textBox1.Text);
        string outVAR = inVAR.ToString();
        textBox2.Text = outVAR;

    }

This of course results in the output being the same as the input, since I am converting the byte array back in to a readable string.

My question is how can I get the ASCII text to convert to binary but also a string type so that I can display it in the text box.

Essentially I am asking how do I create this ASCII to Binary converter because my method seems wrong.

Thanks!

Resolved! Thank you SLaks and OlimilOops:

textBox2.Text = string.Join(" ", inVAR.Select(b => Convert.ToString(b, 2).ToUpper()));
Taurophylax
  • 355
  • 1
  • 4
  • 10
  • 1
    for those who marked it as duplicate: functions given in the answers here return string, whereas the functions in the answers to the other question return byte Array. So imho it is not a duplicate. – OlimilOops Dec 27 '13 at 17:49

3 Answers3

4

It sounds like you want to display the numeric value of each byte, presumably separated by some kind of character:

string.Join("separator", bytes)

If you want to display in a base, you can use LINQ:

bytes.Select(b => Convert.ToString(b, 2))
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
0

If you're willing to use hex instead of straight binary (1s and 0s) you can do the following

var builder = new StringBuilder();
builder.Append("0x");
foreach (var b in inVAR) {
  builder.AppendFormat("{0:x}", b);
}
textBox2.Text = builder.ToString();
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
0

here is a solution waterproof for many situations:

    string stringToHex(string astr)
    {
        return StringToHex(astr, System.Text.Encoding.Default);
    }
    string stringToHex(string astr, System.Text.Encoding enc)
    {
        return bytesToHex(enc.GetBytes(astr));
    }
    string bytesToHex(byte[] bytes)
    {
        if (bytes.Length == 0) return "";
        var sb = new StringBuilder();
        var n = bytes.Length - 1;
        for(int i = 0; i < n; i++) 
        {
            sb.Append(byteToHex(bytes[i]));
            sb.Append(" ");
        }
        sb.Append(byteToHex(bytes[n]));
        return sb.ToString();
    }
    string byteToHex(byte b)
    {
        string hx = Convert.ToString(b, 16).ToUpper();
        if (hx.Length < 2) hx = "0" + hx;
        return hx;
    }
OlimilOops
  • 6,747
  • 6
  • 26
  • 36