bitsets二进制AND操作

Sim*_*Sim 4 c++ bitset

我写了以下几行:

std::bitset<4> bitvec;  //bitset 0000
std::bitset<4> addition; //bitset 0000

addition.set(0); //setting the least significant bit

std::cout << addition << std::endl; //output 0001
std::cout << std::endl;

for(int x = 0; x != 16; ++x) { //addition loop
    std::cout << bitvec << std::endl; //output
    bitvec &= addition; //binary AND
}

std::cout << std::endl;
Run Code Online (Sandbox Code Playgroud)

我期望输出为:

0000
0001
0010
0011
0100
0101
....
Run Code Online (Sandbox Code Playgroud)

但循环只输出'0000'.我错过了什么基本概念?

Pet*_*der 6

逻辑AND 不是添加.

特别,

  0000
& 0001
------
= 0000
Run Code Online (Sandbox Code Playgroud)

这解释了为什么你总能得到0000.

逻辑AND只查看两个位集中的每个位,并且只有在其他两个向量中该位为1时才输出1.举个例子:

  1001
& 1100
------
= 1000
Run Code Online (Sandbox Code Playgroud)

第一位为1的原因是因为其他位集中的第一位是1.其余位是0,因为其中一个位组在该位置具有0.

如果你想要添加,不要使用bitset,只需使用add.

unsigned long a = 0;

for (int i = 0; i < 16; ++i)
{
    std::cout << std::bitset<4>(a) << std::endl;
    ++a;
}
Run Code Online (Sandbox Code Playgroud)

输出:

0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111
Run Code Online (Sandbox Code Playgroud)