# boolean logic question

Discussion in 'C++' started by Kurt Krueckeberg, Sep 23, 2004.

1. ### Kurt KrueckebergGuest

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;
}

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

Kurt Krueckeberg, Sep 23, 2004

2. ### Simon StienenGuest

Kurt Krueckeberg <> wrote:
> 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;
> }
>
> 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
--
Simon Stienen <http://dangerouscat.net> <http://slashlife.de>
»What you do in this world is a matter of no consequence,
The question is, what can you make people believe that you have done.«
-- Sherlock Holmes in "A Study in Scarlet" by Sir Arthur Conan Doyle

Simon Stienen, Sep 23, 2004