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

4
  • have you googled this also SO has several examples as well stackoverflow.com/questions/11654562/… Commented Nov 10, 2014 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. Commented Nov 10, 2014 at 22:59
  • No, I did not expectet the output to contain underscores, I wanted to make it easier to read Commented Nov 10, 2014 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). Commented Nov 10, 2014 at 23:03

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

3

Try

str.Append(Convert.ToString(x[i], 2).PadLeft(8, '0'));

1 Comment

@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.
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).

3 Comments

@DJKRAZE: This answers the question "what am I doing wrong".
before you edited it you just had a question not the coded results
I can't help think that a solution to the problem might be a bit more in keeping with the site too... Though other answers do that now anyway.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.