C++ 如何从布尔结果中得到全部1或全部0?

C++ 如何从布尔结果中得到全部1或全部0?,c++,bit-manipulation,bitwise-operators,C++,Bit Manipulation,Bitwise Operators,我(愚蠢地)认为,如果我将布尔结果true,转换为int并左移,我最终会得到每一位都重复的LSB,显然不是 如果我有一个布尔结果,我想把它转换为真的全1,假的全0,那么(计算上)最便宜的方法是什么 bool result = x == y; unsigned int x = 0; //x becomes all ones when result is true //x becomes all zeros when result is false 也许像这样: bool result = x

我(愚蠢地)认为,如果我将布尔结果true,转换为int并左移,我最终会得到每一位都重复的LSB,显然不是

如果我有一个布尔结果,我想把它转换为真的全1,假的全0,那么(计算上)最便宜的方法是什么

bool result = x == y;

unsigned int x = 0;

//x becomes all ones when result is true
//x becomes all zeros when result is false
也许像这样:

bool result = x == y;

unsigned int z = -result;

也许是这样的:

#include <limits>
#include <stdint.h>

...

uint32_t x, y;

// init x and y with some values

if(x == y) {
  // all bits to 1
  x = std::numeric_limits<uint32_t>::max();
} else {
  // all bits to 0
  x = 0;  
}
#包括
#包括
...
uint32_t x,y;
//用一些值初始化x和y
如果(x==y){
//所有位均为1
x=标准::数值限制::最大值();
}否则{
//所有位均为0
x=0;
}

在IMO中更具可读性的解决方案:

unsigned int set_or_unset_all_bits(bool comp) {
    return comp ? ~0u : 0;
}

像这样的怎么样

int main()
{
      unsigned int x, y;
      bool b = x == y;
      x = b ? std::numeric_limits<size_t>::max() : 0;
}
intmain()
{
无符号整数x,y;
布尔b=x==y;
x=b?标准::数值限制::max():0;
}

如果你想把它变成全1或全0,只需使用and和or运算
我(愚蠢地)认为,如果我把布尔结果true,强制转换为int,然后左移,我会在每一位重复LSB
到底是什么?!如果您将其右移,它可能会工作(不可移植),当然,还可以将其包装在一个命名良好的函数中,因为这段代码是晦涩难懂的。并添加注释。
int
的最大值并非全部为1though@L你是对的,改为使用无符号。@LưuVĩnhPhúc是的,它是:)更正确,因为它不假设负数的两个补码表示。