Bitwise Query

I promise, this is my last question for the day!
I'm trying to query bits within an element of an unsigned character array.
Basically, this should return true if there is a bit at that index.
Any advice will be greatly appreciated!!
1
2
3
4
5
6
7
8
9
10
bool BitArray::Query(unsigned int index) const
{
	unsigned char mask = (int)1;
	double byte = (double)index/BITS_PER_BYTE;//
	mask = mask << index%BITS_PER_BYTE;

	if(barray[index] & (1<<mask) == ( 1 << mask))
		return true;
	else return false;
}


Shouldn't a query be something like (A&B) == B?
where B is the Mask?


Right now it's returning 1 2 3 4 5 6 7, when querying a binary "01010101". whereas it should be only returning the odd numbers
Last edited on
1
2
Shouldn't a query be something like (A&B) == B?
where B is the Mask? 


No. Look at:
a =   00110011
b =   00001000 //3rd bit
a&b = 00000000 //not a or b


As for your code:
How can you query a specific bit in an index with only the index? Wouldn't you need another parameter for which bit you want to check?
Last edited on
I did fix it:
1
2
3
4
5
6
7
	unsigned char mask = (int)1;
	int byte = index/BITS_PER_BYTE;//
	mask = mask << index%BITS_PER_BYTE;

	if((barray[byte]) & (mask))
		return true;
	else return false;


My error was not comparing the byte, I was comparing the bit index value
Topic archived. No new replies allowed.