I want to the bits (0 or one) from a byte in a string but I don't know how? Thanks.
Take a look at Convert.ToString(). You can use it both ways, for the conversion byte->bit-string and vice versa.
byte value = 56;
// There ...
string bits = Convert.ToString(value, 2);
// ...and Back Again
value = Convert.ToByte(bits, 2);
Here's clweek's re-written method, that actually works:
I have used StringBuilder class instead of char array.
Sample: byteToBitsString(157)
prints "00101111"
private string byteToBitsString(byte byteIn)
{
var bitsString = new StringBuilder(8);
bitsString.Append(Convert.ToString((byteIn / 128) % 2));
bitsString.Append(Convert.ToString((byteIn / 64) % 2));
bitsString.Append(Convert.ToString((byteIn / 32) % 2));
bitsString.Append(Convert.ToString((byteIn / 16) % 2));
bitsString.Append(Convert.ToString((byteIn / 8) % 2));
bitsString.Append(Convert.ToString((byteIn / 4) % 2));
bitsString.Append(Convert.ToString((byteIn / 2) % 2));
bitsString.Append(Convert.ToString((byteIn / 1) % 2));
return bitsString.ToString();
}
Or the deluxe variant of the bit banging way to do it:
public static string ToByteFormat(int valIn, int digits)
{
var bitsString = new StringBuilder(digits);
int mask = (1 << digits - 1);
for(int i = 0; i < digits; i++)
{
bitsString.Append((valIn & mask) != 0 ? "1" : "0");
mask >>= 1;
}
return bitsString.ToString();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With