Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a byte to a binary string in c#

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

like image 374
IanCian Avatar asked Aug 27 '10 05:08

IanCian


People also ask

What is byte array in C?

byte array in CAn unsigned char can contain a value from 0 to 255, which is the value of a byte. In this example, we are declaring 3 arrays – arr1, arr2, and arr3, arr1 is initialising with decimal elements, arr2 is initialising with octal numbers and arr3 is initialising with hexadecimal numbers.

What are byte arrays?

A byte array is simply a collection of bytes. The bytearray() method returns a bytearray object, which is an array of the specified bytes. The bytearray class is a mutable array of numbers ranging from 0 to 256.


2 Answers

Just change your code to:

string yourByteString = Convert.ToString(byteArray[20], 2).PadLeft(8, '0'); // produces "00111111" 
like image 85
Kelsey Avatar answered Sep 26 '22 05:09

Kelsey


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 
like image 35
Soul Reaver Avatar answered Sep 22 '22 05:09

Soul Reaver