Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Byte to Binary String C# - Display all 8 digits

I want to display one byte in textbox. Now I'm using:

Convert.ToString(MyVeryOwnByte, 2); 

But when byte is has 0's at begining those 0's are being cut. Example:

MyVeryOwnByte = 00001110 // Texbox shows -> 1110 MyVeryOwnByte = 01010101 // Texbox shows -> 1010101 MyVeryOwnByte = 00000000 // Texbox shows -> <Empty> MyVeryOwnByte = 00000001 // Texbox shows -> 1 

I want to display all 8 digits.

like image 506
Hooch Avatar asked Jan 28 '11 14:01

Hooch


People also ask

How do you convert bytes to binary?

In Java, we can use Integer. toBinaryString(int) to convert a byte to a binary string representative. Review the Integer. toBinaryString(int) method signature, it takes an integer as argument and returns a String.

Is binary and byte array same?

Byte arrays mostly contain binary data such as an image. If the byte array that you are trying to convert to String contains binary data, then none of the text encodings (UTF_8 etc.) will work.


2 Answers

Convert.ToString(MyVeryOwnByte, 2).PadLeft(8, '0'); 

This will fill the empty space to the left with '0' for a total of 8 characters in the string

like image 187
WraithNath Avatar answered Sep 28 '22 12:09

WraithNath


How you do it depends on how you want your output to look.

If you just want "00011011", use a function like this:

static string Pad(byte b) {     return Convert.ToString(b, 2).PadLeft(8, '0'); } 

If you want output like "00011011", use a function like this:

static string PadBold(byte b) {     string bin = Convert.ToString(b, 2);     return new string('0', 8 - bin.Length) + "<b>" + bin + "</b>"; } 

If you want output like "0001 1011", a function like this might be better:

static string PadNibble(byte b) {     return Int32.Parse(Convert.ToString(b, 2)).ToString("0000 0000"); } 
like image 39
Gabe Avatar answered Sep 28 '22 13:09

Gabe