Converting a byte to a binary string in c#

IanCian picture IanCian · Aug 27, 2010 · Viewed 82.4k times · Source

In c# I am converting a byte to binary, the actual answer is 00111111 but the result being given is 111111. Now I really need to display even the 2 0s in front. Can anyone tell me how to do this?

I am using:

Convert.ToString(byteArray[20],2)

and the byte value is 63

Answer

Kelsey picture Kelsey · Aug 27, 2010

Just change your code to:

string yourByteString = Convert.ToString(byteArray[20], 2).PadLeft(8, '0');
// produces "00111111"