如何从布尔结果得到全一或全零

How to get all ones or all zeros from boolean result?

本文关键字:布尔 结果      更新时间:2023-10-16

我(愚蠢地)认为如果我接受布尔值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;

一个更具可读性的解决方案:

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;
}

可能是这样的:

#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;  
}