[Solved] Quickly test QBitArray bytes to see if all are zero
-
wrote on 2 May 2014, 02:32 last edited by
I have a QBitArray that has a bunch of bit flags. I wonder if there is a fast way to test if all the bytes used internally in the QBitArray are zero. I can go through them one bit a time. But seems like it could be done faster if I could get at the bytes.
Thanks
-
wrote on 2 May 2014, 04:03 last edited by
What about:
@
if (bitArray.count(true) == 0) { }
@
The way that is implemented should be much faster than a brute force iteration.Or even this:
@
if (bitArray == QBitArray(bitArray.size(), false)) { }
@
If the bit array size is fixed then you could make the RHS a const outside the if(). -
wrote on 2 May 2014, 11:41 last edited by
The fasted method probably would be to run a memcmp() on the constData() of the QBitArray's internal QByteArray. But that isn't exposed to the public. So you are stuck with count() which already does quite some bit magic...
http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
-
wrote on 2 May 2014, 12:14 last edited by
The count() function does what I needed. But still this is a not perfectly suited for what I want.
My particular need I just wanted a super fast way to see if any bits were set. I don't need to have a count, but this will work fine.
If anyone from Qt is listening, it would be nice if the QBitArray had a fast test to see if any bits were set.
-
wrote on 2 May 2014, 12:44 last edited by
If you exclusively modify the Bit vector through QBitArray.setBit(), you could overwrite that method and update a flag of your own. You'd only need to maintain a counter of the "1" bits that is updated at each call. Then you could check for "all bits are zero" in constant time by reading the counter.
@void MyBitArray::setBit(int i, bool value)
{
if(testBit(i) != value)
{
if(value) m_oneCounter++; else m_oneCounter--;
QBitArray::setBit(i, value)
}
}bool MyBitArray::isAllZeros(void)
{
return (m_oneCounter == 0);
}@ -
wrote on 3 May 2014, 21:10 last edited by
Actually, my second option, using operator==(), will not work. It only tests that the internal pointers are the same and does not check that bits themselves.
1/6