// @topic W020101 Bitwise operators and masks
// @brief examples of <tt>& | ~ <<</tt> operators
// bitwise_ops.cpp
int main()
{
unsigned int bits = 3; // 011 -- user input
unsigned int mask = 1; // 001 -- binary mask
//----------------------------------------------------------
// How many bits does int have?
//----------------------------------------------------------
unsigned int bit_length = sizeof( unsigned int ) * 8;
//----------------------------------------------------------
// Move "1" from the lowest to the highest bit in the mask,
// using the shift left operator:
//----------------------------------------------------------
mask = ( mask << ( bit_length - 1 ) );
//----------------------------------------------------------
// How to clear bits specified by the mask?
//----------------------------------------------------------
bits = bits & ~mask; // bitwise AND (&) and NOT (~) operators
bits &= ~mask; // same using arithmetic assignment
//----------------------------------------------------------
// How to set bits specified by the mask?
//----------------------------------------------------------
bits = bits | mask; // bitwise OR (|) operator
bits |= mask; // same using arithmetic assignment
//----------------------------------------------------------
// How to test if ANY of the bits are set?
//----------------------------------------------------------
if ( bits & mask ) { // bitwise AND (&) operator
// yes, some bits are set
} else {
// no, none of them is set
}
//----------------------------------------------------------
// How to test if ALL of the specified bits are set?
//----------------------------------------------------------
if ( ( bits & mask ) == mask ) {
// yes, all bits are set to "1"
} else {
// no, not all of them are set
}
return 0;
}