Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the byte bits as string

Tags:

string

c#

.net

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

like image 483
Hadad Avatar asked Sep 27 '09 13:09

Hadad


3 Answers

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);
like image 123
VolkerK Avatar answered Oct 02 '22 15:10

VolkerK


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();
    }
like image 29
Gondy Avatar answered Oct 02 '22 14:10

Gondy


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();
    }
like image 42
katzImSack Avatar answered Oct 02 '22 14:10

katzImSack