PHP bitwise operation

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
maingroup
Forum Newbie
Posts: 12
Joined: Thu Apr 24, 2008 2:04 pm

PHP bitwise operation

Post 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???
Hannes2k
Forum Contributor
Posts: 102
Joined: Fri Oct 24, 2008 12:22 pm

Re: PHP bitwise operation

Post by Hannes2k »

Hi,
because if the highest bit it set, the number is represented/interpreted as negativ.

Two's complement
maingroup
Forum Newbie
Posts: 12
Joined: Thu Apr 24, 2008 2:04 pm

Re: PHP bitwise operation

Post 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?
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: PHP bitwise operation

Post 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.
Post Reply