Missing leading 0 on binary conversion

Taurophylax

I recently got an answer to converting an ASCII string to binary....

byte[] inVAR = System.Text.Encoding.ASCII.GetBytes(textBox1.Text);

textBox2.Text = string.Join("", inVAR.Select(b => Convert.ToString(b, 2)));

This just takes text from Box1 and puts the binary equivalent in Box2.

My problem is that the leading 0's on the binary are missing.

For example: "A" gives "1000001" instead of "01000001"

I suppose I could manually append each character with a leading zero, but I am afraid this may break certain characters that should start with a "1" or are already 8 digits.

Any ideas?

Szymon

You can use PadLeft to append the right number of characters. If you already have 8 characters, that won't do anything. If you have less, it will add 0 to make it 8 characters.

textBox2.Text = string.Join("", inVAR.Select(b => Convert.ToString(b, 2)
    .PadLeft(8, '0')));

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related