想知道波浪算子

wanted to know about ~tilde operator?

本文关键字:想知道      更新时间:2023-10-16

我看过很多网站和参考书籍,并且达到了使用波浪(~)运算符进行1的补码的程度,但是当我运行下面的代码片段时,我对它的输出感到惊讶。有人能解释一下输出吗?

下面代码的输出是-11。如有任何帮助,不胜感激。

#include <iostream>
using namespace std;
int main() {
    int x=10;
    cout<<~x;
    return 0;
}

波浪是位非操作符,所以它所做的是反转位。因为int是有符号的,所以它对负数使用2的补码:

00001010 = 10
11110101 = -11

这里所涉及的运算符是http://en.cppreference.com/w/cpp/language/operator_arithmetic按位非运算符,它将数字10的所有位进行反转,以得到数字-11,这是由位反转产生的。

相关文章: