Re: Help with some clever bit operations

From: Date: Tue, 13 Jun 2006 11:40:49 +0000
Subject: Re: Help with some clever bit operations
References: 1 2  Groups: php.general 
Request: Send a blank email to php-general+get-237882@lists.php.net to get a copy of this message
----- Original Message ----- From: "David Tulloh" <david@tulloh.id.au> To: <zorglub_olsen@hotmail.com> 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

« previous php.general (#237882) next »