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?
Use bin()
function:
>>> bin(5)
'0b101'
or str.format
:
>>> '{0:04b}'.format(5)
'0101'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With