Q:

Convert integer to binary in python and compare the bits

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?

A:

Use bin() function:
>>> bin(5)
'0b101'

or str.format:
>>> '{0:04b}'.format(5)
'0101'

A:

Here's a quick function I wrote to check the nth bit of a number: 
def check_nth_bit(num, n):
    return (num>>n)&1

Basically, you bitshift the number n times to the right, which would put the nth digit in the rightmost position, and by bitwise and-ing the new number with 1 (which is all 0's except for in the rightmost position), you can check if that bit is a 1 or a 0. So, you can call this function on num with p1 and p2 and compare the results. 
EDIT: This will be p1 and p2 from the end of the number (least-significant bit), not the beginning. 

A:

You can use format:
>>> format(10, 'b')
'1010'

int is used to convert a number from any base to base 10, and you're trying to use it to convert an integer to binary which is wrong.
>>> int('1010', 2)
10
>>> int('20', 2)
Traceback (most recent call last):
  File "<ipython-input-3-05fc7296a37e>", line 1, in <module>
    int('20', 2)
ValueError: invalid literal for int() with base 2: '20'

