You are not logged in.
Pages: 1
I need to take the decimal 49 and figure out what makes the 49. In this case 32 + 16 + 1.
0 - Idle
1 - Transcoding
2 - Commercial Flagging
4 - Grabbing EPG data
8 - Recording - only valid if flag is 1
16 - Locked
32 - Jobs running or pending
64 - In a daily wakeup/shutdown period
128 - Less than 15 minutes to next wakeup period
255 - Setup is running
I have told to do this you'd use a bitmask, and this handy function will print out the bitmask (binary number)
def int2bitmask(some_int):
bitmask = ""
octal_dict={'0':'000','1':'001','2':'010','3':'011','4':'100','5':'101','6':'110','7':'111'}
for c in oct(some_int)[1:]:
bitmask = bitmask+octal_dict[c]
return bitmask.lstrip('0').rjust(8,'0')
So now I need to take the bitmask and determine which decimal numbers there are. (for 49, its 32 + 16 + 1)
1 1 0 0 0 1 (Binary for 49)
32 16 8 4 2 1 (Decimals)
As you can see 32, 16, and 1 are set.
I know this is a crappy explanation, but hopefully you get what I'm trying to do.
I'm not sure how to go about doing this. Any help would be much appreciated.
Offline
#!/usr/bin/env python
import sys
def int2bitmask(some_int):
bitmask = ""
octal_dict={'0':'000','1':'001','2':'010','3':'011','4':'100','5':'101','6':'110','7':'111'}
for c in oct(some_int)[1:]:
bitmask = bitmask+octal_dict[c]
return bitmask.lstrip('0').rjust(8,'0')
def getValues(bin):
#Assumes there are only 8 bits
bin_dict={0:'128',1:'64',2:'32',3:'16',4:'8',5:'4',6:'2',7:'1',}
nums=[]
for (counter, x) in enumerate(bin):
if x == '1':
nums.append(bin_dict[counter])
return nums
if __name__ == "__main__":
print sys.argv[1]
try:
num=int(sys.argv[1])
except NameError:
print "Need an INT"
sys.exit(2)
print getValues(int2bitmask(num))
Well I wrote this and it seems to give me my desired results, but I am interested to see if there is a better to get the results.
Offline
You need to read up on bitwise operators
for flag in map(lambda x: 2**x, range(9)):
if 49 & flag: print flag
Offline
The bitwise operators might help you clean up your code. They are the traditional way to compare bitmasks:
>>> 49 & 32
32
>>> 49 & 16
16
>>> 49 & 8
0
>>> 49 & 4
0
>>> 49 & 2
0
>>> 49 & 1
1
So you can do:
if 49 & 32:
# do something with the 32 flag
Further, if you want to generate the powers of 2, use the bitshift operator:
>>> for i in range(5):
... print i, 2 << i
...
0 2
1 4
2 8
3 16
4 32
I think with those tools, you can clean up your app quite a bit. :-)
Dusty
Offline
Pages: 1