Understanding the behavior of a single ampersand o

2019-01-18 18:32发布

问题:

I understand that the single ampersand operator is normally used for a 'bitwise AND' operation. However, can anyone help explain the interesting results you get when you use it for comparison between two numbers?

For example;

(6 & 2) = 2
(10 & 5) = 0
(20 & 25) = 16
(123 & 20) = 16

There seems to be no logical link between these results - am I missing something? Online documentation only seems to refer to the comparison of booleans or single bits.

回答1:

Compare the binary representations of each of those.

    110 &     010 =     010
   1010 &    0101 =    0000
  10100 &   11001 =   10000
1111011 & 0010100 = 0010000

In each case, a digit is 1 in the result only when it is 1 on both the left AND right side of the input.



回答2:

You need to convert your numbers to binary representation and then you will see the link between results like 6 & 2= 2 is actually 110 & 010 =010 etc 10 & 5 is 1010 & 0101 = 0000



回答3:

The binary and operation is performed on the integers, represented in binary. For example

110  (6)
010  (2)
--------
010  (2)


回答4:

6     = 0110
2     = 0010 
6 & 2 = 0010

20      = 10100
25      = 11001
20 & 25 = 10000

(looks like you're calculation is wrong for this one)

Etc...



回答5:

Internally, Integers are stored in binary format. I strongly suggest you read about that. Knowing about the bitwise representation of numbers is very important.

That being said, the bitwise comparison compares the bits of the parameters:

Decimal: 6    &    2 = 2
Binary:  0110 & 0010 = 0010


回答6:

The bitwise AND is does exactly that: it does an AND operation on the Bits.

So to anticipate the result you need to look at the bits, not the numbers.

AND gives you 1, only if there's 1 in both number in the same position:

6(110) & 2(010) =  2(010)
10(1010) & 5(0101) = 0(0000)

A bitwise OR will give you 1 if there's 1 in either numbers in the same position:

6(110) | 2(010) =  6(110)
10(1010) | 5(0101) = 15(1111)


回答7:

Bitwize AND matches the bits in binary notation one by one and the result is the bits that are comon between the two numbers.

To convert a number to binary you need to understand the binary system.

For example 6 = 110 binary

The 110 represents 1x4 + 1x2 + 0x1 = 6.

2 then is 0x4 + 1x2 + 0x1 = 2.

Bitwize and only retains the positions where both numbers have the position set, in this case the bit for 2 and the result is then 2.

Every extra bit is double the last so a 4 bit number uses the multipliers 8, 4, 2, 1 and can there fore represent all numbers from 0 to 15 (the sum of the multipliers.)