Приглашаем посетить
Гоголь (gogol-lit.ru)

Section 6.4.  Bitwise Operators

Previous
Table of Contents
Next

6.4. 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 128the 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 numberswhenever it finds a 1 in both values, it puts a 1 into the result in the same place. Here is how that looks:

00110100 (52)
00011100 (28)
00010100 (20)

Therefore, 52 & 28 gives 20.

Perhaps the most common bitwise operator is |, which compares bits in operand one against those in operand two, and returns a result with all the bits set in either of them. For example:

00110100 (52)
11010001 (209)
11110101 (245)

The reason the | (bitwise or) operator is so useful is because it allows you to combine many options together. For example, the flock( ) function for locking files takes a constant as its second parameter that describes how you want to lock the file. If you pass LOCK_EX, you lock the file exclusively; if you pass LOCK_SH, you lock the file in shared mode; and if you pass LOCK_NB, you enable "non-blocking" mode, which stops PHP from waiting if no lock is available. However, what if you want an exclusive lock and to not have PHP wait if no lock is available? You pass LOCK_EX | LOCK_NB, and PHP combines the two into one parameter that does both.


Previous
Table of Contents
Next