C++ biteset

本文通过一个C++程序展示了bitset的基本使用方法,包括初始化、位操作如翻转、设置和重置等,并展示了如何检查bitset中1的数量及转换为无符号长整型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <bitset>
using namespace std;


int main()
{
	
	bitset<8> b1;
	bitset<8> b2("00001111");//不能用非0\1字符初始化或赋值,运行期错误
	bitset<8> b3(0xff);
	bitset<16> b4(0xff);

	if (b2.any())//has 1 bit ?
	{
		cout << "b2 has 1 in bit" << endl;
	}
	cout << "b2 is  " << b2 << endl;
	cout << "b2 size is  " << b2.size() << endl;
	cout << "b2 has " << b2.count() << " 1 in bitset" << endl;
	cout << "the num b2 translate is  " << b2.to_ulong() << endl;
	for (int index = 0; index != 8; ++index)
		cout << b2[index] << " "; 
	cout << endl;
	b2.flip(); 
	//for (int index = 0; index != 8; ++index)
	//	b2.flip(index); 
	for (int index = 0; index != 8; ++index)
		cout << b2[index] << " "; 
	cout << endl;
	b2.set(); 
	//for (int index = 0; index != 8; ++index)
	//	b2.set(index);
	for (int index = 0; index != 8; ++index)
		cout << b2[index] << " "; 
	cout << endl;
	b2.reset(); 
	//for (int index = 0; index != 8; ++index)
	//	b2.reset(index); 
	for (int index = 0; index != 8; ++index)
		cout << b2[index] << " "; 
	cout << endl;
	
	cout << "b1 is  " << b1 << endl;
	cout << "b3 is  " << b3 << endl;
	cout << "b4 is  " << b4 << endl;


	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值