This is the Title of the Book, eMatter Edition
Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.
Expressions and Operators
|
41
Bitwise Operators
The bitwise operators act on the binary representation of their operands. Each oper-
and is first turned into a binary representation of the value, as described in the bit-
wise negation operator entry in the following list. All the bitwise operators work on
numbers as well as strings, but they vary in their treatment of string operands of dif-
ferent lengths. The bitwise operators are:
Bitwise negation (
~
)
The bitwise negation operator changes 1s to 0s and 0s to 1s in the binary repre-
sentations of the operands. Floating-point values are converted to integers before
the operation takes place. If the operand is a string, the resulting value is a string
the
same length as the original, with each character in the string negated.
Bitwise AND (
&
)
The bitwise AND operator compares each corresponding bit in the binary repre-
sentations of the operands. If both bits are 1, the corresponding bit in the result
is 1; otherwise, the corresponding bit is 0. For example,
0755 & 0671
is
0651
. This
is a bit easier to understand if we look at the binary representation. Octal 0755 is
binary 111101101, and octal 0671 is binary 110111001. We can the easily see
which bits are on in both numbers and visually come up with the answer:
111101101
& 110111001
---------
110101001
The binary number 110101001 is octal 0651.
*
You can use the PHP functions
bindec( )
,
decbin( )
,
octdec( )
, and
decoct( )
to convert numbers back and forth
when you are trying to understand binary arithmetic.
If both operands are strings, the operator returns a string in which each charac-
ter is the result of a bitwise AND operation between the two corresponding char-
acters in the operands. The resulting string is the length of the shorter of the two
operands; trailing extra characters in the longer string are ignored. For example,
"wolf" & "cat"
is
"cad"
.
Bitwise OR (
|
)
The bitwise OR operator compares each corresponding bit in the binary repre-
sentations of the operands. If both bits are 0, the resulting bit is 0; otherwise, the
resulting bit is 1. For example,
0755 | 020
is
0775
.
If both operands are strings, the operator returns a string in which each charac-
ter is the result of a bitwise OR operation between the two corresponding char-
acters in the operands. The resulting string is the length of the longer of the two
operands, and the shorter string is padded at the end with binary 0s. For exam-
ple,
"pussy" | "cat"
is
"suwsy"
.
* Here’s a tip: split the binary number up into three groups. 6 is binary 110, 5 is binary 101, and 1 is binary
001; thus, 0651 is 110101001.
,ch02.15294 Page 41 Wednesday, March 13, 2002 11:42 AM