Understanding the behavior of a single ampersand operator (&) on integers

22,158

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

Solution 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

Solution 3

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

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

Solution 4

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)

Solution 5

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

Share:
22,158
Jonathan
Author by

Jonathan

Updated on January 07, 2022

Comments

  • Jonathan
    Jonathan over 2 years

    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
    

    I'm not seeing any logical link between these results and I can only find information on comparing booleans or single bits.