Possible Duplicate:
What does this ~ operator mean here?
Bit not operation in PHP(or any other language probably)可能重复:这个〜运算符在这里意味着什么?在PHP(或任何其他语言)可能没有操作
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?
有人可以用PHP解释我的〜运算符吗?我知道它是一个NOT运算符,但为什么PHP将以下语句转换为变量的负值减一?
$a = 1; echo ~$a // echo -2
$a = 2; echo ~$a // echo -3
$a = 3; echo ~$a // echo -4
3 个解决方案
#1
25
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.
operator~是二进制否定运算符(与布尔否定相反),并且它反转其操作数的所有位。结果是二进制补码算术中的负数。
#2
3
It's a bitwise NOT.
这是一个有点不。
It converts all 1s to 0s, and all 0s to 1s. So 1 becomes -2 (0b111111111110 in binary representation).
它将所有1转换为0,将所有0转换为1。因此1变为-2(二进制表示中为0b111111111110)。
Have a look at the doc http://php.net/manual/en/language.operators.bitwise.php
看一下doc http://php.net/manual/en/language.operators.bitwise.php
#3
2
~
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.
〜翻转号码的所有位。在二进制补码(google it)中,通过翻转所有位然后加1.可以实现数学否定。如果你只做第一步(即:只是翻转位),你就得到加法逆减1。
#1
25
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.
operator~是二进制否定运算符(与布尔否定相反),并且它反转其操作数的所有位。结果是二进制补码算术中的负数。
#2
3
It's a bitwise NOT.
这是一个有点不。
It converts all 1s to 0s, and all 0s to 1s. So 1 becomes -2 (0b111111111110 in binary representation).
它将所有1转换为0,将所有0转换为1。因此1变为-2(二进制表示中为0b111111111110)。
Have a look at the doc http://php.net/manual/en/language.operators.bitwise.php
看一下doc http://php.net/manual/en/language.operators.bitwise.php
#3
2
~
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.
〜翻转号码的所有位。在二进制补码(google it)中,通过翻转所有位然后加1.可以实现数学否定。如果你只做第一步(即:只是翻转位),你就得到加法逆减1。