views:

622

answers:

3

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

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

Firstly, I have an array of byte because there apparantly is no bit type. Should I use Boolean[] ? Then, how can I fill this array? Lastly, if previous statements are solved, I should just return bits[position]

I feel like this should somehow be solved with bitmasks, but I don't know where to start..

Any help would be appreciated

+3  A: 

I suspect BitArray is what you're after. Alternatively, using bitmasks yourself isn't hard:

for (int i=0; i < 32; i++)
{
    if ((value & (1 << i)) != 0)
    {
        Console.WriteLine("Bit {0} was set!", i);
    }
}
Jon Skeet
borisCallens
nvrmind, I found: http://www.meshplex.org/wiki/C_Sharp/Shift_Operators
borisCallens
+1  A: 

Do not use Boolean. Although boolean has only two values, it is actually stored using 32 bits like an int.

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

siz
Not in an array it's not. Nor if you have several boolean fields - they'll (by default, at least) get packed together. Not into single bits, admittedly - but each will only take a single byte, rather than 4. If you have a single boolean field and then an int field, padding will kick in, of course.
Jon Skeet
Yes, that's what I figured. But I'm a bit wandering in the dark here so anything will do :PCurrently trying to 1UP my bitskills ;)
borisCallens
He, and once again I leech some of Jon's knowledge :P
borisCallens
(Basically using a Boolean is equivalent to using a Byte in terms of memory usage.)
Jon Skeet
I stand corrected. Thanks Jon.
siz
+2  A: 
Tmdean
Thanks, verry comprehensible example :)
borisCallens
But still I wonder why the called it BitConverter when actually it is a ByteConverter...
borisCallens
That's a good question, but you can probably imagine that the name "ByteConverter" would cause a different kind of confusion.
Tmdean
Well, it doesn't _really_ convert bytes, it converts arrays of bytes, and it's only using the bytes as a convenient representation of raw bits. The name "ByteConverter" doesn't really give you a sense of what the class does.
Tmdean