c++ 位类型 bitset
c++ 位类型 bitset
头文件
详细说明:http://www.cplusplus.com/reference/bitset/bitset/
使用心得总结:
可以非常方便的去取int或long,或longlong的每一位的bit
可以方便的进行二进制字符串到ulong,ullong的转换
容易将一个字符的ascll码转成bit的表示
#include <string>
#include <iostream>
#include <string.h>
#include <bitset>
using namespace std;
int main()
{
cout<<"a"<<endl;
bitset<8> a("00000011");
cout<<a.count()<<endl;
cout<<a.to_ulong()<<endl;
cout<<sizeof(a.to_ulong())<<endl;
// 忽略了低位的1
cout<<"b"<<endl;
bitset<7> b("10000011");
cout<<b.count()<<endl;
cout<<b.to_ulong()<<endl;
cout<<sizeof(b.to_ulong())<<endl;
// cout<<"c"<<endl;
// bitset<8> c("12345678");
// cout<<c.count()<<endl;
// cout<<c.to_ulong()<<endl;
// cout<<sizeof(c.to_ulong())<<endl;
// cout<<"d"<<endl;
// bitset<8> d("01010189");
// cout<<d.count()<<endl;
// cout<<d.to_ulong()<<endl;
// cout<<sizeof(d.to_ulong())<<endl;
//terminate called after throwing an instance of 'std::invalid_argument'
// what(): bitset::_M_copy_from_ptr
// cout<<"e"<<endl;
// bitset<8> e("asd10110");
// cout<<e.count()<<endl;
// cout<<e.to_ulong()<<endl;
// cout<<sizeof(e.to_ulong())<<endl;
//忽略了高位的0,取低位的64位
cout<<"f"<<endl;
bitset<65> f("00000000000000000000000000000000000000000000000000000000000000001");
cout<<f.count()<<endl;
cout<<f.to_ulong()<<endl;
cout<<sizeof(f.to_ulong())<<endl;
//取了前65位的0,忽略了第66位的1
cout<<"g"<<endl;
bitset<65> g("000000000000000000000000000000000000000000000000000000000000000001");
cout<<g.count()<<endl;
cout<<g.to_ulong()<<endl;
cout<<sizeof(g.to_ulong())<<endl;
//terminate called after throwing an instance of 'std::overflow_error'
// what(): _Base_bitset::_M_do_to_ulong
// cout<<"h"<<endl;
// bitset<65> h("10000000000000000000000000000000000000000000000000000000000000001");
// cout<<h.count()<<endl;
// cout<<h.to_ulong()<<endl;
// cout<<sizeof(h.to_ulong())<<endl;
cout<<"i"<<endl;
bitset<2> i("1101");
cout<<i.count()<<endl;
cout<<i.to_ulong()<<endl;
cout<<sizeof(i.to_ulong())<<endl;
// 猜测,你指定位数n,取给的字符串的前n位,去初始化bitset的每一位。
// 对于to_ulong,从低位不断乘2^i,累计得到最终的数值结果,过大会产生溢出错误
// 对于to_ullong同样
return 0;
}