Convert integer to binary in python and compare the bits -
how convert int n
binary , test each bit of resulting binary number?
i have got following after lot of googling:
def check_bit_positions(n, p1, p2): print int(str(n),2)
however error invalid literal int() base 2
. let me know how can binary form of input number , test each bit @ position p1
, p2
edit:
binary = '{0:b}'.format(n) if list(binary)[p1] == list(binary)[p2]: print "true" else: print "false"
the above code works now, how can check postions p1 , p2 end of list?
use bin()
function:
>>> bin(5) '0b101'
or str.format
:
>>> '{0:04b}'.format(5) '0101'
Comments
Post a Comment