views:

132

answers:

3

hello, I want to the bits (0 or one) from a byte in a string but I don't know how? Thanks.

+5  A: 

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);
VolkerK
A: 

Thanks it is so helpfull but How can I reverse that? convert the string of bits back to a byte?

Hadad
This should be a comment, not an answer.
StriplingWarrior
@StriplingWarrior - That is true, it should be a comment. However, please note that with Hadad's massive 15 rep, he cannot add comments yet. :( [Unless the rules have changed.]
dss539
Good point. It would nevertheless be more appropriate as a new question (perhaps with a link to this one) than as an answer. (For the record, I was not the one who -1'd him.)
StriplingWarrior
Another point: he'd be closer to his requisite 50 points if he accepted a few answers from his previous questions.
StriplingWarrior
Even without the rep he should still be able to comment since it's his question.
Stephan
A: 

I bet there's a cleverer way to do this, but it works:

private string byteToBitsString(byte byteIn)
{
    char[] bits = new char[8];
    bits(0) = Convert.ToString((byteIn / 128) % 2);
    bits(1) = Convert.ToString((byteIn / 64) % 2);
    bits(2) = Convert.ToString((byteIn / 32) % 2);
    bits(3) = Convert.ToString((byteIn / 16) % 2);
    bits(4) = Convert.ToString((byteIn / 8) % 2);
    bits(5) = Convert.ToString((byteIn / 4) % 2);
    bits(6) = Convert.ToString((byteIn / 2) % 2);
    bits(7) = Convert.ToString((byteIn / 1) % 2);
    return bits;
}
clweeks