Python Forum

Full Version: Read bit by bit from a 128 bit number
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am trying to read bit by bit from a 128 bit binary number and want to use it.

I was trying my logic on 8 bit number but not getting the bits in order
def get_bit(value,n):
    return ((value >> n & 1))

for i in range (8):   
    if (get_bit (10100010,i)):
       print"TRUE"
    else:
       print "FALSE"
Output:
1
0
1
0
1
0
1
0
0
You've passed a very big number to your function: 10100010 wasn't treated as you expected, but as ten millions etc... Use get_bit(0b10100010,i) instead.
Thanks scidam for the response. Yes you are right if i add "0b" before the number then it works perfect.
but my number "10100010" passed to "get_bit" is of type "str" which is causing problem. Any suggestions for that.
If x is a binary number as a string int(x, 2) will return an integer with the correct value.

>>> b = '1101'
>>> int(b)
1101
>>> int(b, 2)
13