Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert integer to binary in python and compare the bits

Tags:

python

How to convert a int n into binary and test each bit of the resulting binary number?

I have just got the following after a lot of googling:

def check_bit_positions(n, p1, p2):
    print int(str(n),2)

However i get an error invalid literal for int() with base 2. Let me know how can i get binary form of the input number and test each bit at position p1 and p2

EDIT:

binary = '{0:b}'.format(n)
if list(binary)[p1] == list(binary)[p2]:
     print "true"
 else:
     print "false"

The above code works now, however how can i check for postions p1 and p2 from the end of the list?

like image 841
Tina S Avatar asked Aug 07 '13 18:08

Tina S


1 Answers

Use bin() function:

>>> bin(5)
'0b101'

or str.format:

>>> '{0:04b}'.format(5)
'0101'
like image 170
Rohit Jain Avatar answered Sep 26 '22 03:09

Rohit Jain