bitset
- 功能:将对象转换成二进制保存
- 所需头文件:

bitset<8> bitset1; //无参构造,长度为8,默认每一位为0
bitset<8> bitset2(10); //长度为8,二进制保存,前面用0补充
string str("110101");
bitset<16> bitset3(str); //长度为16,二进制保存,前面用0补充
char c[] = "110101";
bitset<16> bitset4(c); //长度为16,二进制保存,前面用0补充

函数
| 函数 | 功能描述 |
|---|
| count() | 值为1的位数 | | size() | 位长 | | test(pos) | 测试pos处的二进制位是否为1,与0做或运算 | | any() | 是否存在值为1 | | none() | 是否不存在值为1 | | all() | 是否值全为1 | | set(pos) | pos位处的二进制位置为1,与1做或运算 | | reset() | 全部置为0 | | flip() | 全部位逐位取反,即所有的1变为0,0变为1 | | flip(pos) | pos处的值取反 | | to_ulong() | 将二进制转换为unsigned long输出 | | to_string() | 将二进制转换为字符串输出 | | ~bitset | 按位取反,与flip()一样 | | os << bitset | 将二进制位输出到os流,小值在右,大值在左 |
例1
当转化的位数有8位,即bieset<8>,而要转化的有9位,那么最低位删除了
bitset<8> func("110011001");
cout << func << endl; // 转化的位数有8位,而要转化的有9位,最低位删除了

例2
bitset<8> func("11001100");
cout << "11001100" << endl;
cout << "func.count(): " << func.count() << endl; // count函数用来求bitset中1的位数
cout << "func.size(): " << func.size() << endl; // size函数用来求bitset的大小
cout << "func.test(0): " << func.test(0) << endl; // test函数用来查下标处的元素是0还是1,并返回false或true
cout << "func.test(2): " << func.test(2) << endl; //
cout << "func.any(): " << func.any() << endl; // any函数检查bitset中是否有1
cout << "func.none(): " << func.none() << endl; // none函数检查bitset中是否没有1
cout << "func.all(): " << func.all() << endl; // all函数检查bitset中是全部为1

例3
bitset<8> func1("11001100");
cout << "11001100" << endl;
cout << "flip(): " << func1.flip() << endl;
bitset<8> func2("11001100");
cout << "flip(0): " << func2.flip(0) << endl;

例4
bitset<8> func("11001100");
unsigned long num1 = func.to_ulong(); // 将bitset转换成unsigned long类型
unsigned long num2 = func.to_ullong(); // 将bitset转换成unsigned long long类型
string str = func.to_string(); // 将bitset转换成string类型
cout << "11001100" << endl;
cout << "to_ulong(): " << num1 << endl;
cout << "to_ullong(): " << num2 << endl;

|