Reputation: 30605
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
Upvotes: 3
Views: 503
Reputation:
A solution that is more readable IMO:
unsigned int set_or_unset_all_bits(bool comp) {
return comp ? ~0u : 0;
}
Upvotes: 7
Reputation: 6183
Maybe something like that:
#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;
}
Upvotes: 1
Reputation: 307
How about something like
int main()
{
unsigned int x, y;
bool b = x == y;
x = b ? std::numeric_limits<size_t>::max() : 0;
}
Upvotes: 1
Reputation: 212939
Like this, perhaps:
bool result = x == y;
unsigned int z = -result;
Upvotes: 9