C++中bitset的基本运算
时间: 2023-08-10 15:25:37 浏览: 100
c++ bitset实现
5星 · 资源好评率100%
C++中的bitset是一个用于存储二进制位的容器,它可以进行基本的位运算。
以下是bitset的基本运算:
1. set():将所有位设置为1。
2. reset():将所有位设置为0。
3. flip():将所有位取反。
4. operator[]:访问位。
5. count():计算1的位数。
6. to_ulong():将bitset转换为unsigned long。
7. to_ullong():将bitset转换为unsigned long long。
8. operator<<, operator>>:左移、右移位。
示例代码:
```
#include <iostream>
#include <bitset>
using namespace std;
int main()
{
bitset<8> bits1("10100101");
bitset<8> bits2("11001100");
cout << "bits1: " << bits1 << endl;
cout << "bits2: " << bits2 << endl;
cout << "bits1 & bits2: " << (bits1 & bits2) << endl;
cout << "bits1 | bits2: " << (bits1 | bits2) << endl;
cout << "bits1 ^ bits2: " << (bits1 ^ bits2) << endl;
bits1.set();
cout << "bits1.set(): " << bits1 << endl;
bits2.reset();
cout << "bits2.reset(): " << bits2 << endl;
bits1.flip();
cout << "bits1.flip(): " << bits1 << endl;
cout << "bits1[2]: " << bits1[2] << endl;
cout << "bits1.count(): " << bits1.count() << endl;
cout << "bits1.to_ulong(): " << bits1.to_ulong() << endl;
cout << "bits1 << 2: " << (bits1 << 2) << endl;
cout << "bits1 >> 2: " << (bits1 >> 2) << endl;
return 0;
}
```
阅读全文