boolean logic question

K

Kurt Krueckeberg

In the book C++ Gothcas, Gotcha #7 is an example of using boolean logic to
simply code. My question follows this snippet from the book.

"Do you have to count to eight when presented with the following?"
int ctr = 0;
for (int i =0; i < 8; ++i) {
if (options & 1 << (8+i) )
if ( ctr++) {
cerr << "too many options selected";
break;
}

"Instead of this?"
typedef unsigned short Bits;
inline Bits repeated( Bits b, Bits m)
{ return b & m & (b & m) -1; }
//. . .
if ( repeated (options, 0XFF) )
cerr << "Too many options slected";

My Question: Why can't repeated() be written simply as
inline Bits repeated (Bits b, Bits m)
{ return b & m;}

Why is the "& (b & m) - 1" necessary? What is that all about?

Thanks,
Kurt
 
S

Simon Stienen

Kurt Krueckeberg said:
In the book C++ Gothcas, Gotcha #7 is an example of using boolean logic to
simply code. My question follows this snippet from the book.

"Do you have to count to eight when presented with the following?"
int ctr = 0;
for (int i =0; i < 8; ++i) {
if (options & 1 << (8+i) )
if ( ctr++) {
cerr << "too many options selected";
break;
}

"Instead of this?"
typedef unsigned short Bits;
inline Bits repeated( Bits b, Bits m)
{ return b & m & (b & m) -1; }
//. . .
if ( repeated (options, 0XFF) )
cerr << "Too many options slected";

My Question: Why can't repeated() be written simply as
inline Bits repeated (Bits b, Bits m)
{ return b & m;}

Why is the "& (b & m) - 1" necessary? What is that all about?

Thanks,
Kurt

With b & m you get a bitmask. If at least one bit is set, one bit will be
the highest set bit, for example: 0b00010000
If this is the only set bit then x-1 will be a mask with every bit up to
and including the highest set bit being 0 and every less significant bit
set. In this example: 0b00001111. Of course, a bitwise AND of those two
values will return 0.
On the other hand, if another bit was set, too (lets say 0b00010100), the
least significant set bit will be reset and all following bits are set,
resulting in the most significant bit staying set: 0b00010011.
Since the bit stays set, the bitwise AND won't reset this bit and the
result is non-zero.

HTH
Simon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top