如何从布尔结果得到全一或全零
How to get all ones or all zeros from boolean result?
我(愚蠢地)认为如果我接受布尔值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;
}
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- valgrind-hellgrind与泄漏检查的结果不同
- 用C++20 fmt限制结果的总大小
- 如何返回一个类的两个对象相加的结果
- 一个关于在C++中重载布尔运算符的问题
- 提升精神:解析布尔表达式并简化为规范范式
- 使用QProcess执行命令,并将结果存储在QStringList中
- 如果我std::dynamic_pointer_cast并且底层dynamic_cast的结果为null,那么返回的sh
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- 序列化,没有库的整数,得到奇怪的结果
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 它如何返回布尔结果?
- 为什么 SFINAE 没有给出增加布尔值的正确结果?
- 布尔函数`again()`得到相同的结果
- 按位运算结果和布尔值
- C++内存:删除未使用的布尔数组可以将结果从正确更改为错误
- c++ std:: string.Find以布尔表达式返回意外结果
- 如何从布尔结果得到全一或全零
- C++:将按位 AND 的结果分配给布尔值
- 链接布尔值会给出与预期相反的结果