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.
The AMPERSAND operator joins several text strings into one text string. You can also use the Concatenate Function instead of the Ampersand (&) calculation operator.
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.
For integer arguments, the single ampersand ("&")is the "bit-wise AND" operator. The double ampersand ("&&") is not defined for anything but two boolean arguments.
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.
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.
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
The binary and operation is performed on the integers, represented in binary. For example
110 (6)
010 (2)
--------
010 (2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With