~ 位运算符 (波浪线) 的功能是什么
有人可以解释一下 PHP 中的 ~
运算符吗?我知道它是一个NOT-operator,但是为什么PHP将以下语句转换为变量的负值减一?
$a = 1; echo ~$a // echo -2
$a = 2; echo ~$a // echo -3
$a = 3; echo ~$a // echo -4
Can someone explain me the ~
operator in PHP? I know it's a NOT-operator, but why does PHP convert following statement to the negative value of the variable minus one?
$a = 1; echo ~$a // echo -2
$a = 2; echo ~$a // echo -3
$a = 3; echo ~$a // echo -4
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这称为二进制补码算术。您可以在此处阅读更多详细信息。
运算符
~
是一个二元否定运算符(与布尔否定相反),因此,它反转其操作数的所有位。二进制补码运算的结果是负数。This is called the two's complement arithmetic. You can read about it in more detail here.
The operator
~
is a binary negation operator (as opposed to boolean negation), and being that, it inverses all the bits of its operand. The result is a negative number in two's complement arithmetic.这是按位非。
它将所有 1 转换为 0,将所有 0 转换为 1。因此 1 变为 -2(二进制表示为 0b111111111110)。
看看文档
http://php.net/manual/en/language.operators.bitwise。 php
It's a bitwise NOT.
It converts all 1s to 0s, and all 0s to 1s. So 1 becomes -2 (0b111111111110 in binary representation).
Have a look at the doc
http://php.net/manual/en/language.operators.bitwise.php
~
翻转数字的所有位。在二进制补码(google 一下)中,数学求反可以通过翻转所有位然后加 1 来实现。如果您只执行第一步(即:仅翻转位),则加法逆元为负 1。~
flips all the bits of the number. In two's complement (google it), mathematical negation is achievable by flipping all the bits and then adding 1. If you only do the first step (ie: just flip the bits), you have the additive inverse minus 1.