理解 ~ 操作员
Understanding ~ Operator
我正在学习按位运算符,为此我在 tutsplus 上推出了 article。嗯,写的挺好的。我能理解 &
和 |
运算符,但 ~
把事情搞砸了。例如,如文章中所述:
In fact, just as ! flips a boolean from true to false or vice versa,
the ~ operator reverses each binary digit in an integer: from 0 to 1
and 1 to 0.
本文假定 OS 将整数存储为 1 byte
或 8 bits
。我正在关注它。我正在使用 PHP 进行实验。代码如下:
$b = 12;
$NOR = ~$b;
/*
* ------------------------
* | $b | 0 0 0 0 1 1 0 0 | = 12
* ------------------------
* | ~ | 1 1 1 1 0 0 1 1 | = 243 as 1 + 2 + 16 + 32 + 64 + 128 = 243
* ------------------------
* Each digit will be inverted.
*/
echobr($NOR);
即使我们认为 $b
被存储为 32 bit
。那么倒过来的值应该是> 243
。相反,它 returns -13
。 echobr()
是我定义的函数
如果能解释清楚,会很有帮助。
$b = 0000 0000 0000 0000 0000 0000 0000 1100
~$b = 1111 1111 1111 1111 1111 1111 1111 0011 = -13
请注意 PHP 使用 two's complement representation which means that the most significant bit is the sign bit, here '1' refers to '-'. You can read more about the sign bit here Sign bit-Wikipedia。
事实上,对于 PHP 中的任何有符号整数,-$i == ~$i + 1
我正在学习按位运算符,为此我在 tutsplus 上推出了 article。嗯,写的挺好的。我能理解 &
和 |
运算符,但 ~
把事情搞砸了。例如,如文章中所述:
In fact, just as ! flips a boolean from true to false or vice versa, the ~ operator reverses each binary digit in an integer: from 0 to 1 and 1 to 0.
本文假定 OS 将整数存储为 1 byte
或 8 bits
。我正在关注它。我正在使用 PHP 进行实验。代码如下:
$b = 12;
$NOR = ~$b;
/*
* ------------------------
* | $b | 0 0 0 0 1 1 0 0 | = 12
* ------------------------
* | ~ | 1 1 1 1 0 0 1 1 | = 243 as 1 + 2 + 16 + 32 + 64 + 128 = 243
* ------------------------
* Each digit will be inverted.
*/
echobr($NOR);
即使我们认为 $b
被存储为 32 bit
。那么倒过来的值应该是> 243
。相反,它 returns -13
。 echobr()
是我定义的函数
如果能解释清楚,会很有帮助。
$b = 0000 0000 0000 0000 0000 0000 0000 1100
~$b = 1111 1111 1111 1111 1111 1111 1111 0011 = -13
请注意 PHP 使用 two's complement representation which means that the most significant bit is the sign bit, here '1' refers to '-'. You can read more about the sign bit here Sign bit-Wikipedia。
事实上,对于 PHP 中的任何有符号整数,-$i == ~$i + 1