^ 运算符的用途是什么? [重复]

问题描述 投票:0回答:3

^
运算符的用途是什么?这不是幂函数:

#include <iostream>

int main(){
    int x, y;

    cout << (x^y) << endl; /* this is the unkown (X^Y)*/

    return 0;
}
c++ operators xor
3个回答
5
投票

^
运算符是按位
XOR
。以6和12为例

6 的二进制是:

110

12 二进制为:

1100

异或遵循以下规则:“第一个或第二个但不是两者”。这是什么意思?它的真值表应该很清楚:

A     B     A^B
0     0      0
0     1      1
1     0      1
1     1      0

您可以看到唯一的

1
位是设置了或A或B(但不是两者)的位。

回到第一个例子:

A    1100 => 12
B    0110 => 6
A^B  1010 => 10

2
投票

这是异或。如果您想了解更多信息,请参阅此处 https://en.wikipedia.org/wiki/Exclusive_or


2
投票

C++ 中的幂函数是

#include <math.h>
#include <iostream>
int main()
{
    int x, y;
    std::cout << "Give numbers " << std::endl;
    std::cout << "x = ";
    std::cin >> x;
    std::cout << "y = ";
    std::cin >> y;
    std::cout << "Result = " << pow(x, y) << std::endl;
    return 0;

}

您的版本是XOR(逻辑运算),用于例如嵌入式系统等。

© www.soinside.com 2019 - 2024. All rights reserved.