简体   繁体   English

bitsets二进制AND操作

[英]bitsets binary AND operation

I wrote the following lines: 我写了以下几行:

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;

and I expected the output to be: 我期望输出为:

0000
0001
0010
0011
0100
0101
....

But the loop just outputs '0000'. 但循环只输出'0000'。 What basic concept am I missing? 我错过了什么基本概念?

Logical AND is not addition. 逻辑AND 不是添加。

Specifically, 特别,

  0000
& 0001
------
= 0000

Which explains why you always get 0000 . 这解释了为什么你总是得到0000

Logical AND just looks at each bit in both bitsets and only outputs a 1 if that bit is 1 in both of the other vectors. 逻辑AND只查看两个位集中的每个位,并且只有在其他两个向量中该位为1时才输出1。 As an example: 举个例子:

  1001
& 1100
------
= 1000

The reason that first bit is 1 is because the first bit in the other bitsets is 1. The rest are 0 because one of the bitsets has a 0 at that position. 第一位为1的原因是因为其他位集中的第一位是1.其余位是0,因为其中一个位组在该位置具有0。

If you want addition, don't use a bitset, and just use addition. 如果你想要添加,不要使用bitset,只需使用add。

unsigned long a = 0;

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

Output : 输出

0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111

On the first loop cycle bitvec = 0000 addition = 0001 在第一个循环周期bitvec = 0000 addition = 0001

0000 AND 0001 operation will result as 0000 and you assign the 0000 to bitvec and history repeating on the all next loop cycles. 0000 AND 0001操作将产生0000 ,并将0000分配给bitvec并在所有下一个循环周期重复执行历史记录。

Your expected results is a result of simple increment operation or +1 addition, basically just prin x in binary format. 您的预期结果是简单增量操作或+1加法的结果,基本上只是二进制格式的prin x What are you trying to do with bitwise AND ? 什么是你想按位做AND

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM