I am bit confused about a expression I found in some C++ code:
if (m & 1) pmm=-pmm;
I am not a C/C++ coder, so Google gives me two things:<ol><li>& is bitwise AND</li> <li>
if (condition) statement</li> </ol>
So, how does the above statement work?
Should I not require a
if ((m & 1)==0)?
Just to add to the more technical explanations, a simpler way of viewing
if (m & 1) is that is tests whether
m is <em>odd</em> (i.e. not an exact multiple of 2):
if (m & 1) // m is odd (1, 3, 5, 7, 9, ...) - do something else // m is even (0, 2, 4, 6, 8, ...) - do something elseAnswer2:
<strong>m</strong> will be represented in memory as a binary number, in other words: a series of bits. The value <strong>1</strong> will also be represented as a series of bits.
For example (I have chosen 8 bit length for simplicity):
m = 00101101 1 = 00000001
Performing a bitwise operation on <strong>m</strong> will perform the operation you specify, in this case <strong>&</strong> (AND) on each bit at the same position on each binary number on either side of the <strong>&</strong> symbol.
<em>i.e. Bit 1 of result = Bit 1 of m & Bit 1 of the value 1. Bit 2 of result = Bit 2 of m & Bit 2 of the value 1 etc...</em>
So for our example:
00101101 & 00000001 --------- 00000001
Assuming <strong>m</strong> is an integer, the bitwise operation will return an integer. The <strong>if</strong> statement will check if the result is true, and since it is an integer it will be interpreted as true if non-zero.
The result is not zero hence it will return true in our example.
So: By <strong>AND</strong>-ing an integer with 1 you will end up returning true in your code for odd numbers only, since bit 1 is always 1 for odd numbers.Answer3:
This is bitwise AND operator. m & 1 evaluates to 1 if bit 0 is set and every expression that is not 0 is <strong>true</strong> implicitly.
Following are equivalent expressions:
if ((m & 1) == 1) // bitwise AND is 1 if ((m & 1) != 0) // bitwise AND is NOT 0 if (m & 1)
However caution is required if testing more bits. For example m = 1:
if (m & 3) is
true also, but the result is
1. Better is
if ((m & 3) == 3) in this case.