Why and 1 ( &1) bitwise operation always return 0 or 1

12.3k views Asked by At

I just started learning about bit wise operation and want to ask why and 1 ( &1) bitwise operation always return 0 or 1 .

4

There are 4 answers

0
Jaromanda X On
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
0
Mayank Shukla On

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)
0
Pul_P On

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.

1
cinsight On

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