如何从布尔结果中获得全部或全部为零?
我(愚蠢地)认为如果我将true的布尔结果转换为int并将其左移,那么我将最终在每一位都重复LSB,显然不是!
如果我有一个布尔结果,并且我想将其转换为全部为真或全为零,那么最简单的方法是(计算)如何执行此操作?
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;
更易读的解决方案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;
}
链接地址: http://www.djcxy.com/p/75005.html