undefinedfix
Sign in

Why can I & 1 judge parity?

frozenlingon edited in Sat, 29 Oct 2022

Generally, it's not if (&) or short-circuit operator in expressions. What does a single & mean

2 Replies
user611811
commented on Sat, 29 Oct 2022

I don't think the expression upstairs is very good. I'll make a supplement. In the computer, we only know binary system. We generally use decimal system. One characteristic of binary system is that each bit is either 0 or 1. Another characteristic is that if the position is 1, the value of that bit is 2 ^ n [^ this symbol represents the power], and N is the bit of 1. For example, for example, the binary "11" has two digits, so analogy to the rule of decimal "one hundred thousand", here the value of bit 1 (that is, the rightmost 1) is 2 ^ 0 = 1, and its ten digits are 2 ^ 1 = 2, so the total number is 2 + 1 = 3. This is the binary calculation rule. After understanding this rule, you may find that the nth power of 2 (n > 0) must be even, and it will be odd only when bit 0 is 1. So how can we know that the 0 th bit of a number is 1? The answer is bitwise and, which is the "&" operator. Bitwise and is to output the result of two binary numbers according to "1 and 1 are 1, 1 and 0 are 0". For example, two binary numbers "11" (i.e. decimal 3) and "01" (i.e. decimal 1) are bitwise and the result is "01", i.e. decimal 1. After knowing the above two points, you should be able to understand why "I & 1" can judge parity.

zcnfk
commented on Sat, 29 Oct 2022

&Bit operation is to judge from the perspective of bit. The reason for judging parity is that only the first bit of 1 is 1, and the others are all 0. So if you take other numbers to do & operation with him, it will ignore all the bits except the first bit (all other bits become 0). The first bit of odd number is 1, and the first bit of even number is 0, so the phenomenon of judging parity is caused

https://developer.mozilla.org...

lock This question has been locked and the reply function has been disabled.