How to get all ones or all zeros from boolean result?
I (stupidly) thought if I took the boolean result of true, cast to an int and left-shifted it I would end up with the LSB repeated at every bit, obviously not!
If I had a boolean result and I wanted to convert this to all ones for true and all zeros for false, what would be the cheapest way (computationally) to do this?
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/75006.html
上一篇: 慢速按位操作
下一篇: 如何从布尔结果中获得全部或全部为零?