59STL

it2025-07-07  17

59STL_bitset

基本概念示例代码

基本概念

bitset对象的定义和初始化(用unsigned值初始化、用string对象初始化)

bitset对象上的操作

示例代码

#include <iostream> #include <string> #include <bitset> using namespace std; int main() { bitset<32> a(156); //a的大小是32位二进制,全部是0 cout << a << endl; bitset<16> b(0xffff); //赋值 cout << b << endl; bitset<32> c(0xffff); cout << c << endl; bitset<32> d(156); //十进制156会变成二进制 cout << d << endl; string str("11111110000000111100001111"); //string初始化 bitset<32> e(str, 5, 4); //第五位开始,取4位数 cout << e << endl; bitset<32> f(str, str.size()-5); //string的最后五位用来初始化 cout << f << endl; cout << endl; //any()和none()检查是否有1 bool is_set = a.any(); if(is_set) cout << "a里至少有一个1!" << endl; bool is_not_set = a.none(); //没有1 if(is_not_set) cout << "a里没有一个1!" << endl; //count()统计1的个数 size_t bits_set = a.count(); cout << "a里一共有 " << bits_set << " 个1" << endl; cout << "a的大小;" << a.size() << endl; cout << "a里一共有 " << a.size() - bits_set << " 个0" << endl; cout << endl; bitset<32> x; cout << x << endl; x[5] = 1; //使用下标修改值 x.set(7); //set把某一位置为1 cout << x << endl; for(int index=0; index != 32; index += 2) x[index] = 1; cout << x << endl; x.set(); //全部置1 cout << x << endl; x.reset(); //全部置0 cout << x << endl; x.flip(); //取反操作 cout << x << endl; unsigned long y = x.to_ulong(); //变成十进制数 cout << y << endl; bitset<4> fourBits; cout << fourBits << endl; bitset<8> eightBits; cout << "请输入一个八位的二进制序列:"; cin >> eightBits; cout << endl; cout << eightBits << endl; cout << "有 " << eightBits.count() << " 个1" << endl; cout << "有 " << eightBits.size() - eightBits.count() << " 个0" << endl; bitset<8> flipInput(eightBits); flipInput.flip(); cout << flipInput << endl; bitset<8> eightMoreBits; cout << "请输入另外一个八位的二进制序列:"; cin >> eightMoreBits; cout << endl; cout << (eightBits & eightMoreBits) << endl; //位与,且优先级较低 cout << (eightBits | eightMoreBits) << endl; //位或 cout << (eightBits ^ eightMoreBits) << endl; //位亦或 return 0; }
最新回复(0)