Home: www.vipan.com Vipan Singla e-mail: vipan@vipan.com
Bitwise Operators and Bit Masks

Bitwise Operators

  • | (Bitwise OR) sets a bit to 1 if one or both of the corresponding bits in its operands are 1, and to 0 if both of the corresponding bits are 0. In other words, | returns one in all cases except where the corresponding bits of both operands are zero. The resulting bit pattern is the "set" (1 or true) bits of any of the two operands. This property is used to "set" or "turn on" a "flag" (bit set to one) in your flags or options variable regardless of whether that flag was set previously or not. Multiple flag bits can be set if a combo MASK is defined.
    // To set or turn on a flag bit(s)
    flags = flags | MASK;
    // or, more succintly
    flags |= MASK;
  • & (Bitwise AND) sets a bit to 1 if and only if both of the corresponding bits in its operands are 1, and to 0 if the bits differ or both are 0. In other words, a one ANDed with any bit is that bit and a zero ANDed with any bit is zero. This operator is used to check the state of a flag in your flags variable. When you AND your flags variable with the MASK, all zeroes in the MASK will return zero for the corresponding position in flags and all ones in the MASK will return whatever the corresponding bit is set to in your flags variable. Therefore, the bitwise AND operator's evaluates to the MASK itself only if the MASK flags are also set in the flags variable.
    // To check the state of a flag bit(s)
    if ((flags & MASK) == MASK) {
      // flag is set or turned on
      ...
    }
    else {
      //flag is not set or is turned off
      ...
    }

Why the name Bit Mask?

Uses of Bit Masks

Code Examples Using Bitwise Operators