views:

86

answers:

3

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

+2  A: 

You could call the Byte.ToString(string) method, which allows you to pass a format string. The format string could specify "D8", which is 8 decimal digits, which would pad the string with zeroes on the left.

http://msdn.microsoft.com/en-us/library/y11056e9.aspx

Zach
@Zach doing `byteArray[20].ToString("D8")` will not produce the binary value, it will produce `00000063`. +5 for a wrong answer. Has anyone tested it?
Kelsey
+5  A: 

Just change your code to:

string yourByteString = Convert.ToString(byteArray[20], 2).PadLeft(8, '0');
// produces "00111111"
Kelsey
this method will always make the string with 8 digits right? so if i will get a different value for instance 10001111 this will not add new 0s in front
IanCian
@IanCian correct, no matter what there will always be 8 digits so if you supply them all, the `PadLeft` will do nothing but if you don't, it iwll fill in the left over space to the left with 0s.
Kelsey
You're right -- my suggestion wasn't right. I didn't test it.
Zach
A: 

Try this one:

public static String convert(byte b)
{
    StringBuilder str = new StringBuilder(8);
            int[] bl  = new int[8];

    for (int i = 0; i < bl.Length; i++)
    {               
        bl[bl.Length - 1 - i] = ((b & (1 << i)) != 0) ? 1 : 0;
    }

    foreach ( int num in bl) str.Append(num);

    return str.ToString();
}
kofucii