Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Missing leading 0 on binary conversion

Tags:

c#

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?

like image 494
Taurophylax Avatar asked Apr 24 '26 22:04

Taurophylax


2 Answers

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')));
like image 176
Szymon Avatar answered Apr 27 '26 11:04

Szymon


you can just use PadLeft

string.Join("", inVAR.Select(b => Convert.ToString(b, 2).PadLeft(8, '0')));
like image 31
Raphaël Althaus Avatar answered Apr 27 '26 12:04

Raphaël Althaus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!