note 56382 added to language.operators.bitwise
| From: | EricSwanson at osu1 dot php dot net | Date: | Thu, 01 Sep 2005 00:19:38 +0000 |
| Subject: | note 56382 added to language.operators.bitwise | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-94560@lists.php.net to get a copy of this message | ||
Perl vs. PHP implementation of the ^ operator:
After attempting to translate a Perl module into PHP, I realized that Perl's implementation of
the ^ operator is different than the PHP implementation. By default, Perl treats the variables as
floats and PHP as integers. I was able to verify the PHP use of the operator by stating "use
integer;" within the Perl module, which output the exact same result as PHP was using.
The logical decision would be to cast every variable as (float) when using the ^ operator in PHP.
However, this will not yield the same results. After about a half hour of banging my head against
the wall, I discovered a gem and wrote a function using the binary-decimal conversions in PHP.
/*
not having much experience with bitwise operations, I cannot tell you that this is the BEST
solution, but it certainly is a solution that finally works and always returns the EXACT same result
Perl provides.
*/
function binxor($a, $b) {
return bindec(decbin((float)$a ^ (float)$b));
}
//normal PHP code will not yeild the same result as Perl
$result = 3851235679 ^ 43814; //= -443704711
//to get the same result as Perl
$result = binxor(3851235679, 43814); //= 3851262585
//YIPPEE!!!
//to see the differences, try the following
$a = 3851235679 XOR 43814;
$b = 3851235679 ^ 43814; //integer result
$c = (float)3851235679 ^ (float)43814; //same as $b
$d = binxor(3851235679, 43814); //same as Perl!!
echo("A: $a<br />");
echo("B: $b<br />");
echo("C: $c<br />");
echo("D: $d<br />");
----
Manual Page -- http://www.php.net/manual/en/language.operators.bitwise.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+56382
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+56382&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+56382&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+56382&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+56382&report=yes&reason=useless
Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+56382&report=yes&reason=non-english
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+56382&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+56382&report=yes
Search -- http://master.php.net/manage/user-notes.php