Convert byte [] to its string representation in binary format

I need to convert Byte[]to stringthat contain a binary sequence of numbers. I can't use Encodingit because it just encodes bytes into characters!

For example, having this array:

new byte[] { 254, 1 };

I want this output:

"1111111000000001"
+3
source share
5 answers

You can convert any numeric integer primitive to its binary representation as a string with Convert.ToString. Doing this for everyone bytein 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:

, 8 , , , . 8 , :

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

Encoding..

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

: 10101011010

@Quintin Robinson;

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

string hexString = sb.ToString();
+3

, BitArray, , ? , , .

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

s1 = "01-02-03-04-05"
s2 = "012345"
, .

+1

All Articles