I just started learning about bit wise operation and want to ask why and 1 ( &1) bitwise operation always return 0 or 1 .
Why and 1 ( &1) bitwise operation always return 0 or 1
Asked Answered
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
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)
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.
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
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center. –
Supersensible
© 2022 - 2024 — McMap. All rights reserved.
x & 1
returns1
if the least significant bit ofx
is1
else0
.1 & 1 = 1
,0 & 1 = 0
. That's how the operator is defined. – Baroscope