Confusing PHP bitwise NOT behavior

前提是你 提交于 2019-12-13 01:59:05

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/18754198/confusing-php-bitwise-not-behavior

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!