文章目录
位运算符
1 目标
本文的目的是了解c++的位运算符。
2 说明
操作符 | 功能 | 用法 |
---|---|---|
& | 按位与 | a & b |
| | 按位或 | a | b |
^ | 按位异或 | a ^ b |
~ | 按位取反(按位非) | a ~ b |
<< | 左移 | a << b |
>> | 右移 | a >> b |
&= | 按位与赋值 | a &= b |
|= | 按位或赋值 | a |= b |
^= | 按位异或赋值 | a ^= b |
<<= | 左移赋值 | a <<= b |
>>= | 右移赋值 | a >>= b |
3 代码
3.1 按位与 &
#include <iostream>
int main() {
int a = 5; // 0101 in binary
int b = 3; // 0011 in binary
int result = a & b; // 0001 in binary
std::cout << "5 & 3 = " << result << std::endl;
return 0;
}
3.2 按位或 |
#include <iostream>
int main() {
int a = 5; // 0101 in binary
int b = 3; // 0011 in binary
int result = a | b; // 0111 in binary
std::cout << "5 | 3 = " << result << std::endl;
return 0;
}
3.3 按位异或 ^
#include <iostream>
int main() {
int a = 5; // 0101 in binary
int b = 3; // 0011 in binary
int result = a ^ b; // 0110 in binary
std::cout << "5 ^ 3 = " << result << std::endl;
return 0;
}
3.4 按位取反(按位非) ~
#include <iostream>
int main() {
int a = 5; // 0101 in binary
int result = ~a; // 1010 in binary (two's complement representation)
std::cout << "~5 = " << result << std::endl;
return 0;
}
3.5 左移 <<
#include <iostream>
int main() {
int a = 5; // 0101 in binary
int result = a << 1; // 1010 in binary
std::cout << "5 << 1 = " << result << std::endl;
return 0;
}
3.6 右移 >>
#include <iostream>
int main() {
int a = 5; // 0101 in binary
int result = a >> 1; // 0010 in binary
std::cout << "5 >> 1 = " << result << std::endl;
return 0;
}
3.7 按位与赋值 &=
#include <iostream>
int main() {
int a = 5; // 0101 in binary
int b = 3; // 0011 in binary
a &= b; // a = a & b, result is 0001
std::cout << "a &= 3 -> a = " << a << std::endl;
return 0;
}
3.8 按位或赋值 |=
#include <iostream>
int main() {
int a = 5; // 0101 in binary
int b = 3; // 0011 in binary
a |= b; // a = a | b, result is 0111
std::cout << "a |= 3 -> a = " << a << std::endl;
return 0;
}
3.9 按位异或赋值 ^=
#include <iostream>
int main() {
int a = 5; // 0101 in binary
int b = 3; // 0011 in binary
a ^= b; // a = a ^ b, result is 0110
std::cout << "a ^= 3 -> a = " << a << std::endl;
return 0;
}
3.10 左移赋值 <<=
#include <iostream>
int main() {
int a = 5; // 0101 in binary
a <<= 1; // a = a << 1, result is 1010
std::cout << "a <<= 1 -> a = " << a << std::endl;
return 0;
}
3.11 右移赋值 >>=
#include <iostream>
int main() {
int a = 5; // 0101 in binary
a >>= 1; // a = a >> 1, result is 0010
std::cout << "a >>= 1 -> a = " << a << std::endl;
return 0;
}