'Why and 1 ( &1) bitwise operation always return 0 or 1
I just started learning about bit wise operation and want to ask why and 1 ( &1) bitwise operation always return 0 or 1 .
Solution 1:[1]
0 & 0 === 0
0 & 1 === 0
1 & 0 === 0
1 & 1 === 1
therefore any number & 1 will always be either 0 or 1
in binary ... any number
xxxxxxxxxxxxx0
or
xxxxxxxxxxxxx1
where x can be 0 or 1
1 in binary is
00000000000001
so
xxxxxxxxxxxxx1 &
00000000000001 ==
00000000000001
xxxxxxxxxxxxx0 &
00000000000001 ==
00000000000000
Solution 2:[2]
When you perform a & 1 it will always return 0 or 1 depending upon the the last binary digit of a.
Rules:
0 & 0 = 0
0 & 1 = 0
1 & 1 = 1
For example:
a = 5 //5 = 0101
b = a & 1 = 1 //(0101 & 0001)
a = 6 //6 = 0110
b = a & 1 = 0 //(0110 & 0001)
Solution 3:[3]
This is a bitwise operation. Suppose you take 2 & 1. That would be 10 and 01 in binary. Bitwise AND will give 00. BitWise operations with 1 will give 1 or 0 always because 1 has only a significant unit's place in binary. So it cannot return any value other than a 0 or a 1.
Solution 4:[4]
This can be used to check if an integer is odd or even, returning a 0 for False and 1 for True.
is_odd: 1 for odd , 0 for even
odd = number & 1
is_even: 1 for even , 0 for odd
even = number & 1 ^ 1
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jaromanda X |
| Solution 2 | Mayank Shukla |
| Solution 3 | Pul_P |
| Solution 4 | cinsight |
