0

I'm trying to convert a byte array to a string in binary format, but Convert.ToString() returns unexpected results. Can you please tell me what am I doing wrong? Here is the code:

class Program
{
    static void Main(string[] args)
    {
        StringBuilder str = new StringBuilder();
        byte[] x = { 0xB1, 0x53, 0x63 };
        for (int i = 0; i < 3; i++)
        {
            str.Append(Convert.ToString(x[i], 2));
        }
        Console.WriteLine(str);
        Console.ReadLine();
    }
}

The output is:

1011000110100111100011


I expected the output to be:

1011_0001_0101_0011_0110_0011 (0xB15363)

And not:

1011_0001_1010_0111_1000_11

Cristi
  • 1,195
  • 6
  • 17
  • 24
  • have you googled this also `SO` has several examples as well http://stackoverflow.com/questions/11654562/how-convert-byte-array-to-string – MethodMan Nov 10 '14 at 22:58
  • 2
    I don't completely understand the question. Did you really expect there to be underscores? If not, please don't complicate the question by providing something other than the _actual_ literal output that you expected, and which was output instead. – Peter Duniho Nov 10 '14 at 22:59
  • No, I did not expectet the output to contain underscores, I wanted to make it easier to read – Cristi Nov 10 '14 at 23:01
  • The underscores made me assume that you were grouping by bytes (well, half bytes) so my first thought is that you were saying it was truncating the last two digits. Putting delimiters between bytes in the actual output would probably have made it more readable (and probably told you what the problem was given the answers given). – Chris Nov 10 '14 at 23:03

3 Answers3

3

Try

str.Append(Convert.ToString(x[i], 2).PadLeft(8, '0'));
AlexD
  • 32,156
  • 3
  • 71
  • 65
  • @Cristi As **Vlad** wrote, the issue is that there are no leading zeros. It is easy to see by adding an extra space between numbers. – AlexD Nov 10 '14 at 23:09
3

If you pad with zeros you'll get the answer

public static void Main()
{        
    StringBuilder str = new StringBuilder();
    byte[] x = { 0xB1, 0x53, 0x63 };
    for (int i = 0; i < 3; i++)
    {
        str.Append(Convert.ToString(x[i], 2).PadLeft(8, '0'));
    }
    Console.WriteLine(str);
    Console.ReadLine();
}

Fiddle

crthompson
  • 15,653
  • 6
  • 58
  • 80
2

You actually just not get leading zeroes.

01010011 will be just 1010011.

You have to add leading zeroes by any of the possible methods (Convert.ToString doesn't seem to have needed overload). PadLeft is mentioned in other answers, adding new string('0', 8 - s.Length) will do as well (but requires a temporary).

Vlad
  • 35,022
  • 6
  • 77
  • 199