Sudantha
Sudantha

Reputation: 16224

Convert a byte[] to its string representation in binary

I need to convert a Byte[] to a string which contain a binary number sequence. I cannot use Encoding because it just encodes bytes into characters!

For example, having this array:

new byte[] { 254, 1 };

I want this output:

"1111111000000001"

Upvotes: 4

Views: 10715

Answers (5)

Soner Gönül
Soner Gönül

Reputation: 98858

string StringIWant = BitConverter.ToString(byteData);

But i suggest work with Encoding..

string System.Text.Encoding.UTF8.GetString(byte[])

EDIT: For like 10101011010

From @Quintin Robinson's answer;

StringBuilder sb = new StringBuilder();
foreach (byte b in myByteArray)
    sb.Append(b.ToString("X2"));

string hexString = sb.ToString();

Upvotes: 3

Brian
Brian

Reputation: 951

Perhaps you can use the BitArray class to accomplish what you are looking for? They have some sample code in the reference which should be pretty easy to convert to what you are looking for.

Upvotes: 2

Jon
Jon

Reputation: 437774

You can convert any numeric integer primitive to its binary representation as a string with Convert.ToString. Doing this for each byte in your array and concatenating the results is very easy with LINQ:

var input = new byte[] { 254 }; // put as many bytes as you want in here
var result = string.Concat(input.Select(b => Convert.ToString(b, 2)));

Update:

The code above will not produce a result having exactly 8 characters per input byte, and this will make it impossible to know what the input was just by looking at the result. To get exactly 8 chars per byte, a small change is needed:

var result = string.Concat(input.Select(b => Convert.ToString(b, 2).PadLeft(8, '0')));

Upvotes: 13

Gabriel
Gabriel

Reputation: 1443

byte[] bList = { 0, 1, 2, 3, 4, 5 };
string s1 = BitConverter.ToString(bList);
string s2 = "";
foreach (byte b in bList)
{
     s2 += b.ToString();
}

in this case s1 ="01-02-03-04-05"
and s2= "012345"
I don't really get what are you trying to achieve.

Upvotes: 1

Andrew Savinykh
Andrew Savinykh

Reputation: 26349

Will BitConverter.ToString work for you?

Upvotes: 1

Related Questions