Re: Bitwise NOT operator?
| From: | Colin Guthrie | Date: | Fri, 20 Aug 2010 15:39:44 +0000 |
| Subject: | Re: Bitwise NOT operator? | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-307613@lists.php.net to get a copy of this message | ||
'Twas brillig, and Andy McKenzie at 20/08/10 16:10 did gyre and gimble:
> Hey everyone,
>
> I'm really not sure what's going on here: basically, the bitwise
> NOT operator seems to simply not work. Here's an example of what I
> see.
>
> ============Script============
>
> $ cat bintest2.php
>
> <?php
>
> $bin = 2;
> $notbin = ~$bin;
>
> echo "Bin: " . decbin($bin) . " !bin: " . decbin($notbin) .
> "\n";
> echo "Bin: $bin !bin: $notbin\n";
>
>
> ?>
> =============================
>
>
> ============Output============
>
> $ php bintest2.php
> Bin: 10 !bin: 11111111111111111111111111111101
> Bin: 2 !bin: -3
>
> =============================
>
>
> Obviously that's not the expected response. I expect to get something
> more like this:
>
> Bin: 10 !bin: 01
> Bin: 2 !bin: 1
>
>
> Can anyone shed some light on this for me?
The output looks correct to me, so I think it's your expectations that
are incorrect.
You are assuming that you are working with a 2-bit number the in actual
fact you are working with a 32-bit number.
If you did
$bin = 2;
$notbin = ~$bin & 3;
Then this should get the results you want. The bitwise & 3 bit
essentially limits things to a 2-bit number. (3 in binary is represented
by 1's for the two LSBs and 0's for all other bits).
FWIW, the fact that ~2 == -3 is due to twos compliment binary notation:
http://en.wikipedia.org/wiki/Twos_Compliment
Col
--
Colin Guthrie
gmane(at)colin.guthr.ie
http://colin.guthr.ie/
Day Job:
Tribalogic Limited [http://www.tribalogic.net/]
Open Source:
Mandriva Linux Contributor [http://www.mandriva.com/]
PulseAudio Hacker [http://www.pulseaudio.org/]
Trac Hacker [http://trac.edgewall.org/]