Re: testing if just one bit is set...
Salt_Peter wrote:
On Nov 6, 1:42 pm, ".rhavin grobert" <cl...@yahoo.de> wrote:
guess you have a processor that can handle 32bit natively and you have
a 32-bit-int. im now looking for some *ultrafast* way to determine if
an int has more than one bit set. any ideas?
an int is not necessarily 32 bits. That depends on the platform.
bitset has a member function count() which returns a count of bits
set.
Use that. If thats too slow for you, try release mode instead of
debug.
#include <iostream>
#include <bitset>
template< typename T >
bool checkbits(const std::bitset< sizeof(T) * 8 >& r)
What's the "8" for? Consider your own words "depends on the platform"
before giving your answer.
{
return (r.count() > 1) ? true : false;
Wouldn't it be clearer to write
return r.count() > 1;
?
}
Also, consider rewriting so that the type doesn't have to be explicitly
specified. Perhaps something like
template<typename T> bool checkbits(T t)
{
std::bitset<..whatever..> r(t);
...
int main ()
{
int n(257);
std::bitset< sizeof(int) * 8 > b(n);
Here it is again... What's the meaning of "8" here?
for (std::size_t i = b.size(); i > 0; --i)
{
std::cout << b.test(i - 1);
if((i-1)%4 == 0)
std::cout << " ";
}
std::cout << std::endl;
if(checkbits< int >(b))
std::cout << "more than one bit set\n";
else
std::cout << "less than 2 bits set\n";
}
/*
0000 0000 0000 0000 0000 0001 0000 0000
result: less than 2 bits set
*/
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask