eLRuLL
eLRuLL

Reputation: 18799

how to find the bit on the right in python

I am trying to identify if a number is even or odd, and I think that this could be achieved just taking the bit on the left of that number for example:

number    bit      odd
  1       0001      1
  2       0010      0
  3       0011      1
  4       0100      0

So if the last bit is 1 then it is odd and if it is 0 then it is even.

How can I solve this on python? using bitwise operations of course, like the title, I just want to get the last bit of the number.

Thank you.

Upvotes: 2

Views: 146

Answers (3)

Aswin Murugesh
Aswin Murugesh

Reputation: 11070

TO check if a number is even or odd, just use

if a%2:
    #do stuff
 else:
     #do stuff

Upvotes: 0

tessi
tessi

Reputation: 13574

Usually you use the modulo operator for such a task:

1 % 2 # gives you 1 (odd)
2 % 2 # gives you 0 (even)

Upvotes: 0

unutbu
unutbu

Reputation: 879271

Use bitwise-and &:

odd = number & 1

In [24]: for number in range(1, 5):
   ....:     print(number & 1)
   ....:     
   ....:     
1
0
1
0

Upvotes: 6

Related Questions