Wednesday, August 24, 2011

bitwise operators

OR(|): returns one in all cases except where the corresponding bits of both operands are zero. 
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.
// To set or turn on a flag bit(s)
flags |= MASK;

AND(&):This operator is used to check the state of a flag in your 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   ... }

XOR(^): The Bitwise XOR is used to toggle the flag bits of a MASK in your flags variable.
// To toggle a flag bit(s) (on if it was off, off if it was on) flags ^= MASK;

NOT(~): This is useful when "unsetting" or "turning off" a flag.
// To unset or turn off a flag bit(s) flags &= ~MASK;

No comments: