/search.css" rel="stylesheet" type="text/css"/> /search.js">
00001 #!/usr/bin/env python 00002 """ 00003 00004 :: 00005 00006 mask6 = int(''.join(statusL[186:192]), 2) 00007 ValueError: invalid literal for int() with base 2: '0000b1' 00008 00009 """ 00010 00011 class CQPacker(object): 00012 def __init__(self): 00013 pass 00014 00015 def pack(self, statusL): 00016 """ 00017 pack the 192 status into 7 int 00018 statusL: list of status str for 192 PMTs order by channelid, e.g. ['1','1','0',...,'1']. 00019 when CQ service unpack the bits, should follow channelid order. 00020 """ 00021 assert len(statusL)==192, 'packing: length of status str != 192' 00022 mask0 = int(''.join(statusL[0:31]), 2) 00023 mask1 = int(''.join(statusL[31:62]), 2) 00024 mask2 = int(''.join(statusL[62:93]), 2) 00025 mask3 = int(''.join(statusL[93:124]), 2) 00026 mask4 = int(''.join(statusL[124:155]), 2) 00027 mask5 = int(''.join(statusL[155:186]), 2) 00028 mask6 = int(''.join(statusL[186:192]), 2) 00029 return [mask0, mask1, mask2, mask3, mask4, mask5, mask6] 00030 00031 def unpack(self, masks): 00032 """ 00033 upack status from masks, return a list of status str, i.e. ['1','1',...,'1'] 00034 masks: list of mask, i.e. [mask0, mask1, ..., mask6] 00035 """ 00036 statusL = [] 00037 for i in range(7): 00038 unmask = list(bin(masks[i])[2:]) # bin(mask) in form of '0b11' 00039 nbits = len(unmask) 00040 nbitsExp=6 if i==6 else 31 00041 unmask = ['0']*(nbitsExp-nbits) + unmask # in case the first several bit is 0 00042 statusL += unmask 00043 assert len(statusL)==192, 'unpacking: length of status str != 192' 00044 return statusL 00045 00046 00047 00048 if __name__ == '__main__': 00049 packer = CQPacker() 00050 import random 00051 nb = 192 00052 checks = [random.getrandbits(nb) for _ in range(1000)] 00053 checks += [0, (1<<nb) - 1 ] 00054 #checks += [-1] # causes invalid literal for int() with base 2: '0000b1' 00055 00056 for i, st in enumerate(checks): 00057 b = bin(st)[2:] 00058 ist = '0' * (nb - len(b)) + b 00059 print "%-6s %-4s %s " % ( i, len(ist), ist ) 00060 msk = packer.pack(ist) 00061 ost = ''.join(packer.unpack( msk )) 00062 assert ist == ost , (i, ist, ost) 00063 00064 00065