1.与运算(&)
参加运算的两个数据,按二进制位进行"与"运算
运算规则:0&0=0; 0&1=0; 1&0=0; 1&1=1;
两位同时为"1",结果才为"1",否则为0
2.或运算(|)
参加运算的两个对象,按二进制位进行"或"运算
运算规则:0|0=0; 0|1=1; 1|0=1; 1|1=1;
参加运算的两个对象只要有一个为1,其值为1
3.异或运算(^)
参加运算的两个数据,按二进制位进行"异或"运算
运算规则:0^0=0; 0^1=1; 1^0=1; 1^1=0
参加运算的两个对象,如果两个相应位值不同,则该位结果为1,否则为0
#include <iostream>
#include <cstdio>
using namespace std;
void swap1(int *n1, int *n2) {
int temp = *n1;
*n1 = *n2;
*n2 = temp;
}
void swap2(int &n1, int &n2) {
int temp = n1;
n1 = n2;
n2 = temp;
}
void swap3(int *&n1, int *&n2) {
int *temp = n1;
n1 = n2;
n2 = temp;
}
int main() {
int n1, n2;
scanf("%d%d", &n1, &n2);
printf("1.n1:%d,n2:%d\n", n1, n2);
swap(n1, n2);
printf("1.n1:%d,n2:%d\n", n1, n2);
printf("2.n1:%d,n2:%d\n", n1, n2);
swap1(&n1, &n2);
printf("2.n1:%d,n2:%d\n", n1, n2);
printf("3.n1:%d,n2:%d\n", n1, n2);
swap2(n1, n2);
printf("3.n1:%d,n2:%d\n", n1, n2);
printf("4.n1:%d,n2:%d\n", n1, n2);
int *p1 = &n1, *p2 = &n2;
swap3(p1, p2);
printf("4.n1:%d,n2:%d\n", *p1, *p2);
printf("5.n1:%d,n2:%d\n", n1, n2);
n1 = n1 ^ n2;
n2 = n1 ^ n2;
n1 = n1 ^ n2;
printf("5.n1:%d,n2:%d\n", n1, n2);
return 0;
}