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

Jonathan picture Jonathan · Jan 21, 2011 · Viewed 19.3k times · Source

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.

Answer

Jeffrey Hantin picture Jeffrey Hantin · Jan 21, 2011

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.