Re: Bitwise operators and check if an bit is NOT within theflag.
| From: | Mathijs | Date: | Tue, 04 Jul 2006 18:23:03 +0000 |
| Subject: | Re: Bitwise operators and check if an bit is NOT within theflag. | ||
| References: | 1 2 3 4 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-239125@lists.php.net to get a copy of this message | ||
Jochem Maas wrote:
Mathijs wrote:It will sure help me understanding it better :).Jochem Maas wrote:...Mathijs wrote:Thank you very much. This seems to work :).cool. heres's a couple of funcs that might help you to understand bitwise operations better: <?php /* whether there is only 1 single bit set or not */ function single_bit_set(/*int*/ $i) {// beware: if $i is zero !($i & ~get_ls1bit($i)) returns true; return $i ? !($i & ~get_ls1bit($i)): false;} /* return the value of the least significant bit */ function get_ls1bit(/*int*/ $i) {for ($j = 1; $i && !($i & $j); $j <<= 1); return $i ? $j : 0;} /* return the value of the most significant bit */ function get_ms1bit(/*int*/ $i) {$x = 0; for ($j = $i; $i && !($j == 1); $j >>= 1) { $x++; } return $i ? $j <<= $x: 0;} /* doesn't break when exponents are near the wordsize * of the machine as the native xor does, here is some example code to * illustrate: php -r '// include function definition here $x = 3851235679; $y = 43814; echo "\nThis is the value we want"; echo "\n3851262585";echo "\nThe result of a native xor operation on integer values is treated as a signed integer"; echo "\n".($x ^ $y);echo "\nWe therefore perform the MSB separately"; echo "\n".get_xor32($x, $y)."\n";' */ function get_xor32(/*int*/ $a, /*int*/ $b) {$a1 = $a & 0x7FFF0000; $a2 = $a & 0x0000FFFF; $a3 = $a & 0x80000000; $b1 = $b & 0x7FFF0000; $b2 = $b & 0x0000FFFF; $b3 = $b & 0x80000000;$c = ($a3 != $b3) ? 0x80000000 : 0;return (($a1 ^ $b1) |($a2 ^ $b2)) + $c;} function get_bit_str($var, $safety = 0) {$rtn = '';$var = intval($var); if ($var < 0) { $var = 0 - $var; }while ($var != 0 /*&& $safety < 31*/) { $rtn .= ($var & 1); $var >>= 1; $safety++; }return $rtn;} Thx alot :).