Reputation: 2149
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'.
Upvotes: 1
Views: 199
Reputation: 29668
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');
Upvotes: 3