Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

Bitwise Operators

Bitwise operators aren't used very often, and even then only by more advanced PHP programmers. They manipulate the binary digits of numbers, which is more control than many programmers need. The bitwise operators are listed in Table 6-4.

Table 6-4. The bitwise operators

&

And

Bits set in $a and $b are set.

|

Or

Bits set in $a or $b are set.

^

Xor

Bits set in $a or $b, but not both, are set.

~

Not

Bits set in $a are not set, and vice versa.

<<

Shift left

Shifts the bits of $a to the left by $b steps. This is equivalent, but faster, to multiplication. Each step counts as "multiply by two." If you try this with a float, PHP ignores everything after the decimal point and treats it as an integer.

>>

Shift right

Shifts the bits of $a to the right by $b steps.

To give an example, the number eight is represented in eight-bit binary as 00001000. In a shift left, <<, all the bits literally get shifted one place to the left, giving 00010000, which is equal to sixteen. Eight shifted left by four gives 10000000, which is equal to 128—the same number you would have gotten by multiplying eight by two four times in a row.

The & (bitwise and) operator compares all the bits in operand one against all the bits on operand two, then returns a result with all the joint bits set. Here's an example: given 52 & 28, we have the eight-bit binary numbers 00110100 (52) and 00011100 (28). PHP creates a result of 00000000, then proceeds to compare each digit in both numbers—whenever ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page