Page 81 - Beginning PHP 5.3
P. 81
Chapter 3: PHP Language Basics
Operator Description Example
^ (Xor) Bits set in either value (but 14 ^ 3 = 13
not both) are set in the result 00001110 | 00000011 = 00001101
~ (Not) Bits set in the value are not set ~14 = - 15
in the result, and vice versa ~00000000000000000000000000001110
=
11111111111111111111111111110001
< < (Shift left) Shifts all bits in the first value 3 < < 2 = 12
a number of places to the left 00000011 < < 2 = 00001100
(specified by the second value)
> > (Shift right) Shifts all bits in the first value 8 > > 2 = 2
a number of places to the right 00001000 > > 2 = 00000010
(specified by the second value)
You can see that ~ (Not) inverts all the bits in the number. Notice that there are 32 bits in each value,
because PHP uses 32 - bit integers. (The other examples show only the last 8 bits of each value, for
brevity.) The resulting bit values ( 11111111111111111111111111110001 ) represent – 15, because
PHP uses the two ’ s complement system to represent negative numbers (see http://en.wikipedia
.org/wiki/Two%27s_complement for an explanation of two ’ s complement).
A common usage of bitwise operators is to combine values together to make a bit mask . For example,
consider the constants representing PHP ’ s error levels (described in detail in Chapter 20 ). The E_NOTICE
constant has an integer value of 8 (00001000 in binary), and the E_PARSE constant has an integer value of
4 (00000100 in binary). To combine these two constants so that both E_NOTICE and E_PARSE levels are
reported, you ’ d use the | (bitwise Or) operator:
E_NOTICE | E_PARSE
This combines the bits of the two integer constants together to create a new integer (12) whose bit values
represent both E_NOTICE (8) and E_PARSE (4):
00001000 (8) | 00000100 (4) = 00001100 (12)
Comparison Operators
As you might imagine from the name, comparison operators let you compare one operand with the other
in various ways. If the comparison test is successful, the expression evaluates to true ; otherwise, it
evaluates to false . You often use comparison operators with decision and looping statements such as
if and while (these are covered in Chapter 4 ).
43
9/21/09 8:51:24 AM
c03.indd 43
c03.indd 43 9/21/09 8:51:24 AM