我(愚蠢地)认为如果我将布尔结果转换为true,则转换为int并左移它我最终会在每一位重复LSB,显然不是!
如果我有一个布尔结果并且我想将其转换为全部为true而所有零都为false,那么最简单的方法(计算)是什么?
bool result = x == y;
unsigned int x = 0;
//x becomes all ones when result is true
//x becomes all zeros when result is false
答案 0 :(得分:9)
像这样,也许:
bool result = x == y;
unsigned int z = -result;
答案 1 :(得分:7)
更易读的解决方案IMO:
unsigned int set_or_unset_all_bits(bool comp) {
return comp ? ~0u : 0;
}
答案 2 :(得分:1)
也许是这样的:
#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;
}
答案 3 :(得分:1)
像
这样的东西int main()
{
unsigned int x, y;
bool b = x == y;
x = b ? std::numeric_limits<size_t>::max() : 0;
}