59STL_bitset
基本概念示例代码
基本概念
bitset对象的定义和初始化(用unsigned值初始化、用string对象初始化)
bitset对象上的操作
示例代码
#include <iostream>
#include <string>
#include <bitset>
using namespace std
;
int main()
{
bitset
<32> a(156);
cout
<< a
<< endl
;
bitset
<16> b(0xffff);
cout
<< b
<< endl
;
bitset
<32> c(0xffff);
cout
<< c
<< endl
;
bitset
<32> d(156);
cout
<< d
<< endl
;
string
str("11111110000000111100001111");
bitset
<32> e(str
, 5, 4);
cout
<< e
<< endl
;
bitset
<32> f(str
, str
.size()-5);
cout
<< f
<< endl
;
cout
<< endl
;
bool is_set
= a
.any();
if(is_set
)
cout
<< "a里至少有一个1!" << endl
;
bool is_not_set
= a
.none();
if(is_not_set
)
cout
<< "a里没有一个1!" << endl
;
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);
cout
<< x
<< endl
;
for(int index
=0; index
!= 32; index
+= 2)
x
[index
] = 1;
cout
<< x
<< endl
;
x
.set();
cout
<< x
<< endl
;
x
.reset();
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;
}
转载请注明原文地址: https://win8.8miu.com/read-1548847.html