Velvet Star Monitor

Standout celebrity highlights with iconic style.

updates

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

Writer Mia Lopez

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

10

4 Answers

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

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy