meaning of & in C++

2019-09-20 16:14发布

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:

  1. & is bitwise AND
  2. if syntax is if (condition) statement

So, how does the above statement work? Should I not require a if ((m & 1)==0)?

3条回答
再贱就再见
2楼-- · 2019-09-20 16:52

m will be represented in memory as a binary number, in other words: a series of bits. The value 1 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 m will perform the operation you specify, in this case & (AND) on each bit at the same position on each binary number on either side of the & symbol.

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...

So for our example:

  00101101
& 00000001
 ---------
  00000001

Assuming m is an integer, the bitwise operation will return an integer. The if 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 AND-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.

查看更多
别忘想泡老子
3楼-- · 2019-09-20 16:55

Just to add to the more technical explanations, a simpler way of viewing if (m & 1) is that is tests whether m is odd (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 else
查看更多
可以哭但决不认输i
4楼-- · 2019-09-20 16:56

This is bitwise AND operator. m & 1 evaluates to 1 if bit 0 is set and every expression that is not 0 is true 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.

查看更多
登录 后发表回答