Page 1 of 1
PHP bitwise operation
Posted: Fri Nov 21, 2008 2:23 pm
by maingroup
my PHP is 32-bit.
<?php
$a = 1;
echo $a << 31;
?>
This output is
-2147483648
2 to 31st power = 2147483648. But why the negative???
Re: PHP bitwise operation
Posted: Fri Nov 21, 2008 2:28 pm
by Hannes2k
Hi,
because if the highest bit it set, the number is represented/interpreted as negativ.
Two's complement
Re: PHP bitwise operation
Posted: Fri Nov 21, 2008 3:27 pm
by maingroup
Thanks for the info and link.
Here is another question.
<?php
$a = 2147483648;
echo $a>>1;
?>
2 to the 31st power = 2147483648. I right shift one position, instead of giving me 2^30. It gives -673741824. Why?? The 32nd bit now is 0, but why the out put is still negative?
Re: PHP bitwise operation
Posted: Fri Nov 21, 2008 4:05 pm
by requinix
Uh, I get -1073741824, which makes more sense than yours.
Code: Select all
$a=2147483647;
echo gettype($a),"<br/>\n";
$a=2147483648;
echo gettype($a),"<br/>\n";
When you pass the integer limit PHP converts it to a floating-point number, which means the whole "32nd bit is the sign" thing doesn't apply anymore.