Reputation: 67
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.
Upvotes: 1
Views: 2066
Reputation: 726479
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
.
Upvotes: 4
Reputation: 11
The && is the and
logical operator. It returns true if both left and right expressions are true.
The & is the and
bitwise operator. Returns the bits that are set on both left and right operands.
Well, this requires further explanation.
Basically, the & operator looks at individual bytes. For instance, consider:
int x = 1; int y = 2;
In this case, x
has 1 bit set (it's, well, 1) and y
has 1 bit set too (it's 10, 2 in binary).
So, x & y
would yield 01 & 10
and, consequently, 0, because there are no bits that are set on both x
and y
.
In your case, it will return true if x
is true AND the negation of x & x1
is something other than 0, because 0 is a falsy value.
See: https://msdn.microsoft.com/en-us/library/17zwb64t.aspx
Upvotes: 1