Python Forum
Read bit by bit from a 128 bit number
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Read bit by bit from a 128 bit number
#1
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
Reply
#2
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.
Reply
#3
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.
Reply
#4
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
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Read directory listing of files and parse out the highest number? cubangt 5 2,251 Sep-28-2022, 10:15 PM
Last Post: Larz60+
  csv.reader(): Limit the number of columns read in Windows Pedroski55 9 5,042 Jan-23-2021, 01:03 AM
Last Post: pjfarley3
  Can't read url when specifying more than a specific number of bytes deivid 3 3,034 Aug-13-2018, 02:24 PM
Last Post: deivid

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020