In addition to the answer of "dasblinkenlight" I think an example could help. I will only use 8 bits for a better understanding.
x & 1
produces a value that is either 1
or 0
, depending on the least
significant bit of x
: if the last bit is 1
, the result of x & 1
is 1
;
otherwise, it is 0
. This is a bitwise AND operation.
This is because 1
will be represented in bits as 00000001
. Only the last bit is set to 1
. Let's assume x
is 185
which will be represented in bits as 10111001
. If you apply a bitwise AND operation on x
with 1
this will be the result:
00000001
10111001
--------
00000001
The first seven bits of the operation result will be 0
after the operation and will carry no information in this case (see Logical AND operation). Because whatever the first seven bits of the operand x
were before, after the operation they will be 0
. But the last bit of the operand 1
is 1
and it will reveal if the last bit of operand x
was 0
or 1
. So in this example the result of the bitwise AND operation will be 1
because our last bit of x
is 1
. If the last bit would have been 0
, then the result would have been also 0
, indicating that the last bit of operand x
is 0
:
00000001
10111000
--------
00000000
x >>= 1
means "set x
to itself shifted by one bit to the right". The
expression evaluates to the new value of x
after the shift
Let's pick the example from above. For x >>= 1
this would be:
10111001
--------
01011100
And for left shift x <<= 1
it would be:
10111001
--------
01110010
Please pay attention to the note of user "dasblinkenlight" in regard to shifts.
&
,>>=
, and other operators are notoriously hard to search on the internet. The question is simple for someone who has seen these operators before, but they are not self-explanatory, and could be quite overwhelming when you see them for the first time. – Cervinesizeof
suggests thatsizeof x * CHAR_BIT
would give the right answer. But the code in the question only measures the count of significant bits in a particular argument (i.e. not counting zero-bits before the first 1-bit). These are different things. – Nelson-1
you probably ought to use~0U
to set all the bits to 1. – Berlin