简体   繁体   中英

How can I convert a byte into a string of binary digits in C#?

I am trying to convert a byte into a string of binary digits - not encoded, just as it is, ie 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'.

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM