没有对C语言中位的理解,你一定不会用std::bitset,如果理解里C中的位操作,就真心不必再使用std::bitset了
#include "iostream"
#include <iomanip>
void printBits(unsigned int value)
{
constexpr int size = 8 * sizeof(unsigned);
constexpr int mask = (1<<(size - 1));
std::cout << std::setw(2);
for(int i = 1;i <= size;++i)
{
std::cout << ((mask & value) ? '1' : '0');
value <<= 1;
if(i%8 == 0)
std::cout <<' ';
}
}
#define PRINT1(a) std::cout << std::setw(8) << #a" ="; \
printBits(a); \
std::cout << std::endl;
int main(int,char**)
{
unsigned int a = 0xff;
unsigned int b = 3;
PRINT1(a);
PRINT1(b);
PRINT1(a&b);
PRINT1(a|b);
PRINT1(a^b);
PRINT1(a&~b);
PRINT1(a^=b);
PRINT1(a^=b);
return 0;
}
上面的程序的输出如下:
view.png
网友评论