Re: Bitwise NOT operator?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On 20 August 2010 17:10, Andy McKenzie <amckenzie4@xxxxxxxxx> wrote:
> 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 server is running an
> old version of OpenSUSE, and php --version returns:
>

You probably need to read up on computer architechture and CS theory -
the ~ operator works fine, your understanding does not. What you're
looking at is the following:

$bin = 2 = 00000000000000000000000000000010 (64 bit number)
~$bin = ~2 = -3 = 11111111111111111111111111111101 (the inverse of the above)

Computers generally do not operate on a couple of bits from a byte -
they tend to operate on a byte, a word, a doubleword, etc (before any
nitpickers interrupt: sure, they can, but most operations don't).
Hence, you're not doing a not operation on just "10", you're doing it
on "00000000000000000000000000000010". And as you are operating on a
signed int, you'll get a negative number out of the ~ operation
(seeing as you flipped the most significant bit).

Regards
Peter

-- 
<hype>
WWW: http://plphp.dk / http://plind.dk
LinkedIn: http://www.linkedin.com/in/plind
BeWelcome/Couchsurfing: Fake51
Twitter: http://twitter.com/kafe15
</hype>

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php




[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux