bitsets二进制AND运算 [英] bitsets binary AND operation

查看:235
本文介绍了bitsets二进制AND运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了以下行:

  std :: bitset< 4> bitvec; // bitset 0000 
std :: bitset< 4>加成; // bitset 0000

addition.set(0); //设置最低有效位

std :: cout<<添加< std :: endl; // output 0001
std :: cout< std :: endl;

for(int x = 0; x!= 16; ++ x){//加法循环
std :: cout< bitvec<< std :: endl; // output
bitvec& = addition; // binary and
}

std :: cout<< std :: endl;

我希望输出为:

  0000 
0001
0010
0011
0100
0101
....

但是循环只输出'0000'。

解决方案

逻辑AND是 b
$ b

具体来说,

  0000 
& 0001
------
= 0000

总是获得 0000

$



逻辑AND仅查看两个位组中的每个位,只输出1在其他向量中为1。例如:

  1001 
& 1100
------
= 1000

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



如果你想添加,不使用bitset,只需使用添加。

  unsigned long a = 0; 

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

输出

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


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'. What basic concept am I missing?

解决方案

Logical AND is not addition.

Specifically,

  0000
& 0001
------
= 0000

Which explains why you always get 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. 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.

If you want addition, don't use a bitset, and just use addition.

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

这篇关于bitsets二进制AND运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆