Bitwise Operators


PHP also comes with a set of operators that can work with the individual bits in an integer. You don't usually use the bitwise operators unless you've had some experience programming and want to work with individual bits in various values. If you don't know about bits, bytes, and so on, don't worry; you can skip this chunk without harm.

NOTE

Besides integers, you can also work with strings using these operators; in that case, the ASCII value of each character is used.


For example, the And operator, &, works on two operands like this: $a | $b. In the result, bits that are set (that is, equal to 1, not 0) in either $a or $b are set. So, for example, if $a equals 1 (which has the 0th bit set) and $b = 2 (which has the 1st bit set), then $a | $b will equal 1 | 2; both the 0th bit and the 1st bit are set in the result, so it equals 3.

You can see the bitwise operators and what they do in Table 2-2.

Table 2-2. The Bitwise Operators

Operator

Operation

Example

Result

$a & $b

And

$a & $b

Bits that are set in both $a and $b are set.

$a | $b

Or

$a | $b

Bits that are set in either $a or $b are set.

$a ^ $b

Xor

$a ^ $b

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

~ $a

Not

~ $a

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

$a << $b

Shift left

$a << $b

Shift the bits of $a $b steps to the left (each step means "multiply by two").

$a >> $b

Shift right

$a >> $b

Shift the bits of $a $b steps to the right (each step means "divide by two").


Notice the shift operators here, which let you shift bits to the right or the left. For example, 4 << 1 means that we're shifting the bits in the value 4 left one place, which ends up giving you 8 (the same as multiplying by 2). Conversely, 4 >> 1 shifts the bits in 4 to the right one place, giving you 2 (the same as dividing by 2).

These operators are meant to work on the bits in individual integers, not on boolean values, and, as mentioned, this kind of work is usually only performed by programmers who have special needs to work with those bits. If you do need this kind of bit-by-bit functionality, however, it's available for you in PHP.



    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net