Why does BitConverter return bytes and how can I get bits?

I get an int as input (well, actually, a string that I have to convert to int).
This int must be converted to bit.
For every bit position that has 1, I have to get the position.
In my database, I want all records to have an int value field that has this position as value.
I currently have the following naive code that should query my entity (maintaining the database) if it matches a position, but obviously doesn't work correctly:

Byte[] bits = BitConverter.GetBytes(theDatabaseValue);
return bits[position].equals(1);

      

First, I have a byte array because apparantly is not a bit type. Should I use Boolean []? Then, how can I fill this array? Finally, if the previous statements are resolved, I should just return the [position] bit

It seems to me that this should somehow be resolved with bitmax, but I don't know where to start ..

Any help would be appreciated

0


source to share


3 answers


Your feeling is correct. This needs to be solved with bitmax. BitConverter doesn't return bits (and how can that be?) "Bit" is not an actual data type, it converts raw bytes to CLR data types. Whenever you want to extract a bit from something, you have to think about bitmasks.

If you want to check if a bit is set at a specific position, use the and operator. Bitwise and only effective if both bits are set. For example, if you had two bytes 109 and 33, the result would be

  0110 1101
& 0010 0001
-----------
  0010 0001


If you just want to know if a bit is set to an int, you and it with a number that only the bit you are checking has (i.e. 1, 2, 4, 8, 16, 32, and so on) and check if whether the result is zero.

List<int> BitPositions(uint input) {
    List<int> result = new List<int>();
    uint mask = 1;
    int position = 0;
    do {
        if (input & mask != 0) {
            result.Add(position);
        }
        mask <<= 1;
        position++;
    } while (mask != 0);

    return result;
}

      

+4


source


I suspect BitArray is what you need. Alternatively, using bitmasks yourself is not difficult:



for (int i=0; i < 32; i++)
{
    if ((value & (1 << i)) != 0)
    {
        Console.WriteLine("Bit {0} was set!", i);
    }
}

      

+4


source


Don't use Boolean. Although boolean only has two values, it is actually stored using 32 bits like int.

EDIT: Actually, in array form, Booleans will be packed into bytes, not 4 bytes.

+1


source







All Articles