The Bitwise Operators
The Bitwise Operators
The bitwise operators are similar to the logical operators, except that they work on a
smaller scale -- binary representations of data.
• op1 & op2 -- The AND operator compares two bits and generates a result of 1 if
both bits are 1; otherwise, it returns 0.
• op1 | op2 -- The OR operator compares two bits and generates a result of 1 if the
bits are complementary; otherwise, it returns 0.
• op1^ op2 -- The EXCLUSIVE-OR operator compares two bits and returns 1 if
either of the bits are 1 and it gives 0 if both bits are 0 or 1.
• ~op1 -- The COMPLEMENT operator is used to invert all of the bits of the
operand.
• op1 >> op2 -- The SHIFT RIGHT operator moves the bits to the right, discards
the far right bit, and assigns the leftmost bit a value of 0. Each move to the right
effectively divides op1 in half.
• op1 << op2 -- The SHIFT LEFT operator moves the bits to the left, discards the
far left bit, and assigns the rightmost bit a value of 0. Each move to the left
effectively multiplies op1 by 2.
Note Both operands associated with the bitwise operator must be integers.
Bitwise operators are used to change individual bits in an operand. A single byte of
computer memory-when viewed as 8 bits-can signify the true/false status of 8 flags
because each bit can be used as a boolean variable that can hold one of two values: true
or false. A flag variable is typically used to indicate the status of something. For instance,
computer files can be marked as read-only. So you might have a $fReadOnly variable
whose job would be to hold the read-only status of a file. This variable is called a flag
variable because when $fReadOnly has a true value, it's equivalent to a football referee
throwing a flag. The variable says, "Whoa! Don't modify this file."
Reference: http://www.cs.cf.ac.uk/Dave/PERL/node36.html
0 0 0 0 0
1 0 1 0 1
0 1 1 0 1
1 1 1 1 0
Reference: http://www.vipan.com/htdocs/bitwisehelp.html