I'm not entirely sure what happens in this process and what the outcome would be. I've never come across using && in a return or especially a single one in the same return statement.
bool myfunction(unsigned int x)
{
return x && !(x & (x - 1));
}
I'd love some clarification as to what happens here and why. I've been looking around but msdn is down and can't seem to find any concrete answers about this type of return.
Here is what it means:
x
part means x != 0
(x & (x-1))
part means "x
is not a power of two" (i.e. is zero or has more than one bit set)!(x & (x-1))
expression means "x
is a power of two"Therefore, overall expression means "x
is a positive power of two".
To see why x & (x-1)
helps you find powers of two, consider what happens to numbers that have a single bit set vs. the numbers that have two or more bits set. A number with a single bit set, when decremented, would produce a sequence that looks like this:
000100000..000 <== x
000011111..111 <== x-1
When you apply bitwise-and to a pair of numbers like that, you get zero, because the only bit that has been set in x
is now zero, and all the bits set in x-1
were zeros in x
.
When the number has two or more bits set, the pattern would look like this:
010100000..000 <== x
010011111..111 <== x-1
Now the last bit that was set would be cleared, but all bits ahead of it would remain set to 1
, producing a non-zero pattern when "AND"-ed with the original value of x
.