Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

c# - 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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...