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