Getting the byte bits as string

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

Answers


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;
}

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();
    }

Here's one bit banging way to do it:

public static string ByteToBinaryString(byte byteIn)
{
    StringBuilder out_string = new StringBuilder();
    byte mask = 128;
    for (int i = 7; i >=0 ; --i)
    {
        out_string.Append((byteIn & mask) != 0 ? "1" : "0");
        mask >>= 1;
    }
    return out_string.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();
    }

Need Your Help

Sort multidimensional array by multiple keys

php arrays sorting multidimensional-array

I'm trying to sort a multidimensional array by multiple keys, and I have no idea where to start. I looked at uasort, but wasn't quite sure how to write a function for what I need.

Correct use of `= delete` for methods in classes

c++ c++11 operator-overloading move-semantics rvalue-reference

Is the following snipplet correct for un-defining all otherwise generated methods and constructors for a class?