Converting a byte to a binary string in c#

C#StringBinaryByte

C# Problem Overview


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

C# Solutions


Solution 1 - C#

Just change your code to:

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

Solution 2 - C#

If I understand correctly, you have 20 values that you want to convert, so it's just a simple change of what you wrote.

To change single byte to 8 char string: Convert.ToString( x, 2 ).PadLeft( 8, '0' )

To change full array:

byte[] a = new byte[] { 1, 10, 100, 255, 200, 20, 2 };
string[] b = a.Select( x => Convert.ToString( x, 2 ).PadLeft( 8, '0' ) ).ToArray();
// Returns array:
// 00000010
// 00010100
// 11001000
// 11111111
// 01100100
// 00001010
// 00000001

To change your byte array to single string, with bytes separated with space:

byte[] a = new byte[] { 1, 10, 100, 255, 200, 20, 2 };
string s = string.Join( " ",
    a.Select( x => Convert.ToString( x, 2 ).PadLeft( 8, '0' ) ) );
// Returns: 00000001 00001010 01100100 11111111 11001000 00010100 00000010

if ordering of bytes is incorrect use IEnumerable.Reverse():

byte[] a = new byte[] { 1, 10, 100, 255, 200, 20, 2 };
string s = string.Join( " ",
    a.Reverse().Select( x => Convert.ToString( x, 2 ).PadLeft( 8, '0' ) ) );
// Returns: 00000010 00010100 11001000 11111111 01100100 00001010 00000001

Solution 3 - C#

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();
}

Solution 4 - C#

public static string ByteArrayToString(byte[] ba)
{
    StringBuilder hex = new StringBuilder(ba.Length * 2);
    foreach (byte b in ba)
        hex.AppendFormat("{0:x2}", b);
    return hex.ToString();
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIanCianView Question on Stackoverflow
Solution 1 - C#KelseyView Answer on Stackoverflow
Solution 2 - C#Soul ReaverView Answer on Stackoverflow
Solution 3 - C#kofuciiView Answer on Stackoverflow
Solution 4 - C#Mahmoud El-bazView Answer on Stackoverflow