1

In PHP, if I run the following simple program

$number = 9;
var_dump( ~ $number );

my output is

int(-10)

This is confusing to me. I thought ~ was the bitwise NOT operator. So I was expecting something like.

if binary 9 is     00000000000000000000000000001001 
then Bitwise NOT 9 11111111111111111111111111110110

Meaning ~9 should come out as some ludicrously large integer like 4,294,967,286.

What subtly of precedence, type coercion, or something else am I missing here?

4

1 回答 1

3

Your output is defaulting to a signed int - wrap it in decbin to get a binary representation.

Consider:

$number = 9;
var_dump(  bindec(decbin(~ $number)) );

With two's compliment, the MSB of a signed binary number becomes 0-MSB, but every other bit retains its respective positive values.

So for argument's sake (an 8-bit example),

Binary 9: 0000 1001
Inverse:  1111 0110

This results in (-128) + 64 + 32 + 16 + 4 + 2 = -10, so PHP is calculating correctly, its just applying two's compliment to the MSB.

于 2013-09-12T02:21:50.217 回答