----- Original Message ----- From: "David Tulloh" <[EMAIL PROTECTED]>
To: <[EMAIL PROTECTED]>
Cc: <php-general@lists.php.net>
Sent: Tuesday, June 13, 2006 12:18 PM
Subject: Re: [PHP] Help with some clever bit operations


The example starting values
$existing = 181; # = 10110101
$new = 92; # = 01011100
$mask = 15; # = 00001111

Get the bits that will be changed
$changing = $new & $mask; # = 12 = 00001100

Get the bits that won't be changed
$staying = $existing & ~$mask; # = 176 = 10110000

Combine them together
$result = $changing ^ $staying; # = 188 = 10111100


David


Though the result is the same, logically a bitwise OR (|) would be more appropriate. The bitwise XOR flips bits which, since in this case one set of them is always 0 produces the same result. The bitwise OR adds the bits.

An informal set of rules is:

&, as a filter, extracts those bits where you put ones in the mask
& sets to zero those bits where you put zero in the mask
| sets bits
^ flips the bits where you put a one.

$evenodd & 1 is true on odd numbers or otherwise tests for the rightmost bit. Coupled with a right shift >> allows you to loop through a set of bits.

for ($i=0;$i<32;$i++) {
   if ($bitset & 1) {
       echo "bit $i is set";
   }
   $bitset >>= 1;
}

Anyway, avoid the most significant bit. Since in PHP there are no unsigned integers, you might get some funny result if anything makes PHP do an automatic type conversion.

Satyam

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to