bitset用法

发布时间 2023-10-31 11:53:18作者: 小海哥哥de

1、简介

bitset 在 bitset 头文件中,它类似数组,并且每一个元素只能是0或1,每个元素只用1bit空间。

//头文件
#include<bitset>

2、初始化定义

初始化方法

代码 含义
bitset a a有n位,每位都为0
bitset a(b) a是unsigned long型u的一个副本
bitset a(s) a是string对象s中含有的位串的副本
bitset a(s,pos,n) a是s中从位置pos开始的n个位的副本

注意:n必须为常量表达式
演示代码:

#include<bits/stdc++.h>
using namespace std;
int main() {
	bitset<4> bitset1;    //无参构造,长度为4,默认每一位为0
	
	bitset<9> bitset2(12); //长度为9,二进制保存,前面用0补充
	
	string s = "100101";
	bitset<10> bitset3(s);  //长度为10,前面用0补充
	
	char s2[] = "10101";
	bitset<13> bitset4(s2);  //长度为13,前面用0补充
	
	cout << bitset1 << endl;  //0000
	cout << bitset2 << endl;  //000001100
	cout << bitset3 << endl;  //0000100101
	cout << bitset4 << endl; //0000000010101
	return 0;
}

3、特性

bitset可以进行位操作

bitset<4> foo (string("1001"));
bitset<4> bar (string("0011"));

cout << (foo^=bar) << endl;// 1010 (foo对bar按位异或后赋值给foo)

cout << (foo&=bar) << endl;// 0001 (按位与后赋值给foo)

cout << (foo|=bar) << endl;// 1011 (按位或后赋值给foo)

cout << (foo<<=2) << endl;// 0100 (左移2位,低位补0,有自身赋值)

cout << (foo>>=1) << endl;// 0100 (右移1位,高位补0,有自身赋值)

cout << (~bar) << endl;// 1100 (按位取反)

cout << (bar<<1) << endl;// 0110 (左移,不赋值)

cout << (bar>>1) << endl;// 0001 (右移,不赋值)

cout << (foo==bar) << endl;// false (1001==0011为false)

cout << (foo!=bar) << endl;// true  (1001!=0011为true)

cout << (foo&bar) << endl;// 0001 (按位与,不赋值)

cout << (foo|bar) << endl;// 1011 (按位或,不赋值)

cout << (foo^bar) << endl;// 1010 (按位异或,不赋值)

访问

//可以通过 [ ] 访问元素(类似数组),注意最低位下标为0,如下:
bitset<4> foo ("1011"); 

cout << foo[0] << endl;  //1
cout << foo[1] << endl;  //0
cout << foo[2] << endl;  //1

4、方法函数

代码 含义
b.any() b中是否存在置为1的二进制位,有 返回true
b.none() b中是否没有1,没有 返回true
b.count() b中为1的个数
b.size() b中二进制位的个数
b.test(pos) 测试b在pos位置是否为1,是 返回true
b[pos] 返回b在pos处的二进制位
b.set() 把b中所有位都置为1
b.set(pos) 把b中pos位置置为1
b.reset() 把b中所有位都置为0
b.reset(pos) 把b中pos位置置为0
b.flip() 把b中所有二进制位取反
b.flip(pos) 把b中pos位置取反
b.to_ulong() 用b中同样的二进制位返回一个unsigned long值

原文链接:https://blog.csdn.net/qq_50285142/article/details/114186789