混淆PHP按位NOT行为
在PHP中,如果我运行以下简单程序
In PHP, if I run the following simple program
$number = 9;
var_dump( ~ $number );
我的输出是
int(-10)
这让我感到困惑.我认为 ~
是按位的NOT
运算符.所以我期待着类似的事情.
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
含义~9
应该以类似于4,294,967,286
的一些荒谬的大整数形式出现.
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?
您的输出默认为带符号的int-将其包装在decbin中以获取二进制表示形式.
Your output is defaulting to a signed int - wrap it in decbin to get a binary representation.
考虑:
$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.
因此,为了论证(一个8位示例),
So for argument's sake (an 8-bit example),
Binary 9: 0000 1001
Inverse: 1111 0110
结果为(-128) + 64 + 32 + 16 + 4 + 2 = -10
,因此PHP可以正确计算,只需对MSB应用2的补码即可.
This results in (-128) + 64 + 32 + 16 + 4 + 2 = -10
, so PHP is calculating correctly, its just applying two's compliment to the MSB.