1

I am trying to convert a byte into a string of binary digits - not encoded, just as it is, i.e. if the byte = 00110101 then the string would be "00110101".

I have searched high and low, and everything I find is either relating to getting the ASCII or UTF or whatever value of the byte, or converting a character into a byte, neither of which is what I want. Just doing ToString() gives me the int value.

Maybe i'm missing something obvious, and I understand this is a fairly rare case. It must be possible without some crazy loop which iterates through, surely?

(I'm sending the string over bluetoothLE to a rotating shop display cabinet to program it)

edit: here's some code:

DateTime updateTime = DateTime.Now;
byte dow = (byte)updateTime.DayOfWeek;
Debug.WriteLine(dow.ToString());

If I break and inspect 'dow', it shows as '3' (it's wednesday), not 00000011 as I would have expected. I just tried BitConverter as suggested below, but that still returns '3'.

Ryan
  • 2,109
  • 1
  • 15
  • 19
  • Post your code. What type is byte? – Sriram Sakthivel Feb 26 '14 at 10:01
  • Try using BitConverter http://msdn.microsoft.com/en-us/library/system.bitconverter.tostring(v=vs.110).aspx – ilansch Feb 26 '14 at 10:02
  • posible duplicate http://stackoverflow.com/questions/3702216/how-to-convert-integer-to-binary-string-in-c http://stackoverflow.com/questions/3581674/converting-bytes-to-a-binary-string-in-c-sharp – wiero Feb 26 '14 at 10:11

1 Answers1

3

You want to use Convert.ToString() but specify a base, in this case because it's binary, base 2.

However, you'll also need to pad to the number of bits, because it will cut off 0 digits, so 00000001 would end up as 1.

Try this:

Convert.ToString(theByte,2).PadLeft(8,'0');
Lloyd
  • 29,197
  • 4
  • 84
  • 98