Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 563
Jonathan Avatar asked Jan 21 '11 10:01

Jonathan


People also ask

What is the ampersand operator?

The AMPERSAND operator joins several text strings into one text string. You can also use the Concatenate Function instead of the Ampersand (&) calculation operator.

What does a single ampersand mean in C++?

The bitwise AND operator in C++ is a single ampersand & , used between two other integer expressions. Bitwise AND operates on each bit position of the surrounding expressions independently, according to this rule: if both input bits are 1, the resulting output is 1, otherwise the output is 0.

What does single & operator mean?

For integer arguments, the single ampersand ("&")is the "bit-wise AND" operator. The double ampersand ("&&") is not defined for anything but two boolean arguments.

What does a single ampersand mean in Java?

If both the operands are true, then the condition becomes true otherwise it is false. Assume boolean variable A holds true and variable B holds false then (A && B) is false. & is to be used during bitwise operations and && is useful during logical operations.


3 Answers

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.

like image 69
Jeffrey Hantin Avatar answered Oct 24 '22 03:10

Jeffrey Hantin


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

like image 6
Valentin Kuzub Avatar answered Oct 24 '22 03:10

Valentin Kuzub


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

110  (6)
010  (2)
--------
010  (2)
like image 4
abesto Avatar answered Oct 24 '22 02:10

abesto