php ~ 按位运算符 (波浪号) 的功能是什么

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9129744/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 06:13:17  来源:igfitidea点击:

What's the function of the ~ bitwise operator (Tilde)

phpoperatorsbit-manipulationtilde

提问by Michiel

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-operator,但为什么 PHP 将以下语句转换为变量的负值减去一?

$a = 1; echo ~$a    // echo -2
$a = 2; echo ~$a    // echo -3
$a = 3; echo ~$a    // echo -4  

回答by buc

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.

该运算符~是一个二元否定运算符(与布尔否定相反),因此,它反转其操作数的所有位。结果是二进制补码运算中的负数。

回答by akond

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

看看文档 http://php.net/manual/en/language.operators.bitwise.php

回答by cHao

~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。