def test_setitem(): x = nitarray('0,2,1,1,0,0,2', 3) assert_equal(x._bitarray, ba.bitarray('00100101000010')) x[1:3] = 0 assert_equal(x._bitarray, ba.bitarray('00000001000010')) x[1:3] = '1,2' assert_equal(x._bitarray, ba.bitarray('00011001000010')) x[-5:-2] = [2, 2, 1] assert_equal(x._bitarray, ba.bitarray('00011010010010')) x[-2:] = nitarray([1, 0], 3) assert_equal(x._bitarray, ba.bitarray('00011010010100')) x[:3] = 2 assert_equal(x._bitarray, ba.bitarray('10101010010100')) x[0] = 0 assert_equal(x._bitarray, ba.bitarray('00101010010100')) x[2] = '1' assert_equal(x._bitarray, ba.bitarray('00100110010100')) x[-2] = [2] assert_equal(x._bitarray, ba.bitarray('00100110011000')) x[-1] = nitarray([2], 3) assert_equal(x._bitarray, ba.bitarray('00100110011010'))
def __init__(self): self.header_bits = bitarray(8) self.data_bits = bitarray() self.header_bits[0] = 0 # Mandatory value self.header_bits[1:7] = 0 # These bits must be filled in by a subclass self.header_bits[7] = 0 # TODO: Wasted bits
def bitarray_from_int(i, width): assert i < 2**width if width == 0: return bitarray() return bitarray(('{:0' + str(width) + 'b}').format(i))
def make_restrictions(self, fields=None): "構造体のビット列を生成する際に attribute に対して制約条件を決定する" if not fields: self.rests = {} fields = self._fields_ for attr, ctrl, stat in reversed(fields): if isinstance(ctrl, int): "条件文内の attr がすでに存在していればあらかじめ bit 値を生成しておく" self.setattr_bit(attr, bitarray('0', endian='big')) # False for a, c, s in stat: if hasattr(self, a) and self.getattr_bit(a) != None: self.setattr_bit(attr, bitarray('1', endian='big')) # True break self.make_restrictions(stat) elif hasattr(self, attr) and getattr(self, attr) != None: """ (attr, ctrl=type, stat=bit_length) なのでサイズ制約を決定 ex. ('n_rotate_bits', UB, 5) ('has_scale', UB, 1) ('scale_x', FB, 'n_scale_bits') """ if stat != 1: # flag はすでに上記で設定しているので制約条件は設定しない self.rests[attr] = stat if isinstance(stat, str): "可変長サイズの場合は、attr の長さに応じてあらかじめ stat に bit 値を設定しておく" if not hasattr(self, stat) or getattr(self, stat) == None: self.setattr_value(stat, 0) self.setattr_value( stat, max(self.getattr_value(stat), len(self.getattr_bit(attr)))) else: setattr(self, attr, None)
def utf8_encoded_bitarray_from_int(i): # i < 2**7 if i < 0x80: return bitarray_from_int(i, 8) # i < 2**11 if i < 0x800: bits = bitarray(16) bits[0:8] = bitarray_from_int(0xC0 | (i >> 6), 8) bits[8:16] = bitarray_from_int(0x80 | (i & 0x3F), 8) return bits # i < 2**16 if i < 0x10000: bits = bitarray(24) bits[0:8] = bitarray_from_int(0xE0 | (i >> 12), 8) bits[8:16] = bitarray_from_int(0x80 | ((i >> 6) & 0x3F), 8) bits[16:24] = bitarray_from_int(0x80 | (i & 0x3F), 8) return bits # i < 2**21 if i < 0x200000: bits = bitarray(32) bits[0:8] = bitarray_from_int(0xF0 | ((i >> 18)), 8) bits[8:16] = bitarray_from_int(0x80 | ((i >> 12) & 0x3F), 8) bits[16:24] = bitarray_from_int(0x80 | ((i >> 6) & 0x3F), 8) bits[24:32] = bitarray_from_int(0x80 | (i & 0x3F), 8) return bits # i < 2**26 if i < 0x4000000: bits = bitarray(40) bits[0:8] = bitarray_from_int(0xF0 | ((i >> 24)), 8) bits[8:16] = bitarray_from_int(0x80 | ((i >> 18) & 0x3F), 8) bits[16:24] = bitarray_from_int(0x80 | ((i >> 12) & 0x3F), 8) bits[24:32] = bitarray_from_int(0x80 | ((i >> 6) & 0x3F), 8) bits[32:40] = bitarray_from_int(0x80 | (i & 0x3F), 8) return bits # i < 2**31 if i < 0x80000000: bits = bitarray(40) bits[0:8] = bitarray_from_int(0xF0 | ((i >> 24)), 8) bits[8:16] = bitarray_from_int(0x80 | ((i >> 18) & 0x3F), 8) bits[16:24] = bitarray_from_int(0x80 | ((i >> 12) & 0x3F), 8) bits[24:32] = bitarray_from_int(0x80 | ((i >> 6) & 0x3F), 8) bits[32:40] = bitarray_from_int(0x80 | (i & 0x3F), 8) return bits assert False, "We shouldn't need to encode any integers that require more than 31 bits"
def __init__(self, start_id, size, parent_id, histogram, level = None): ''' @summary: Node Constructor @param start_id: Root结点为0 @param size: 项总数(包含&) @param parent_id: Root结点为-1 @param histogram: 对应可能孩子结点计数 @param level: 树层数, Root为1 ''' self.start_id = start_id self.histogram = histogram # 记录父结点 self.parent_id = parent_id self.childrens = np.array([None] * size) # 标记扰动计数为哪一种类型, 以决定 epsilon # True: 噪音计数 # False: 预测计数, epsilon 有节省(由于最初始由噪音计数计算得来, 满足E-DP) self.noised = bitarray([True] * size) # 标记是否已发布 - children # bitarray 用以初始化 0/1 self.released = bitarray([False] * size) self.size = size self.level = level self.left_level = None self.eps = None
def test_created_pool(self): obj = DummyObject(42) pool = DummyPool(obj) self.assertEqual(pool.to_01(), '1' * 42) self.assertEqual(pool.to_map(), '.' * 42) self.assertEqual(pool.available, bitarray('1' * 42 + '0' * 6)) self.assertEqual(pool.reserved, bitarray('1' * 42 + '0' * 6))
def otherinteractions(resdict, residuechoice, protein, ligand): for residue in OBResidueIter(protein): residuename = residue.GetName() if residuename in residuechoice: for atom in OBResidueAtomIter(residue): if not atom.IsHydrogen(): for atomlig in OBMolAtomIter(ligand): if not atomlig.IsHydrogen(): distance = atom.GetDistance(atomlig) if distance <= 4.5: if isnonpolar(atomlig) & isnonpolar(atom): resdict[residuename] |= bitarray('1000000') if distance <= 4.0: setformalcharge(atom) setformalcharge(atomlig) if (atom.GetFormalCharge()>0) & (atomlig.GetFormalCharge()<0): resdict[residuename] |= bitarray('0000010') if (atom.GetFormalCharge()<0) & (atomlig.GetFormalCharge()>0): resdict[residuename] |= bitarray('0000001') if distance <= 3.5: if atom.IsHbondDonor() & atomlig.IsHbondAcceptor(): donorresidue = atom.GetResidue() for atomres in OBResidueAtomIter(donorresidue): if atomres.IsHbondDonorH() & atomres.IsConnected(atom): angle = atom.GetAngle(atomres, atomlig) if angle>135.0: resdict[residuename] |= bitarray('0001000') if atom.IsHbondAcceptor() & atomlig.IsHbondDonor(): for atomres in OBMolAtomIter(ligand): if atomres.IsHbondDonorH() & atomres.IsConnected(atomlig): angle = atomlig.GetAngle(atomres, atom) if angle>135.0: resdict[residuename] |= bitarray('0000100')
def getresiduedict(protein, residuechoice): resdict = {} for residue in OBResidueIter(protein): resdict[residue.GetName()] = bitarray('0000000') for residue in residuechoice: resdict[residue] = bitarray('0000000') return resdict
def stringToBitarray(s, bitarray_lib_path=bitarray_lib_path): sys.path.append(bitarray_lib_path) from bitarray import bitarray d = {'A':bitarray('000'), 'T':bitarray('001'),'C':bitarray('010'),'G':bitarray('011'),'N':bitarray('100')} b = bitarray() b.encode(d,s) return b
def type2(font): old_12_method = change_method(_c_m_a_p.cmap_format_12_or_13,_decompile_in_cmap_format_12_13, 'decompile') cmapTable = font['cmap'] cmap12 = cmapTable.getcmap(3, 10).cmap #format 12 assert cmap12,'cmap format 12 table is needed' ourData = cmap12 deltaCodePoints = generateDeltaArray(ourData['startCodes']) lengths = ourData['lengths'] deltaGids = generateDeltaArray(ourData['gids']) nGroups = len(deltaGids) gos_data = bitarray.bitarray(endian='big') extra_data = bitarray.bitarray(endian='big') gos_data.frombytes(struct.pack('>B',2)) #GOS type gos_data.frombytes(struct.pack('>H',nGroups)) for idx in xrange(nGroups): delta_code_result = NumberEncoders.AOE(deltaCodePoints[idx],3) add_to_extra_if_necessary(gos_data, extra_data, delta_code_result) len_result = NumberEncoders.AOE(lengths[idx],2) add_to_extra_if_necessary(gos_data, extra_data, len_result) gid_result = NumberEncoders.AOE(deltaGids[idx],3) add_to_extra_if_necessary(gos_data, extra_data, gid_result) change_method(_c_m_a_p.cmap_format_12_or_13,old_12_method,'decompile') whole_data = gos_data.tobytes() + extra_data.tobytes() #print 'type2 size',len(whole_data) return whole_data
def crea_guarda_archivo(nombre_archivo,imagen,tabla_codigos,cadena01): dim_x = imagen.shape[1] dim_y = imagen.shape[0] archivo_abierto = False n_entradas = len(tabla_codigos.items) try: archivo = open(nombre_archivo,"w") archivo_abierto = True except IOError: print 'No se pudo crear: '+nombre_archivo+"!" if archivo_abierto == True: try: archivo.write(convierte_a_bytes(dim_x)) archivo.write(convierte_a_bytes(dim_y)) archivo.write(convierte_a_bytes(n_entradas)) for i in tabla_codigos.items: bit_array = bitarray(i.codigo,endian='big') tam_codigo = len(i.codigo) archivo.write(chr(i.simbolo)) archivo.write(chr(tam_codigo)) archivo.write(bit_array.tobytes()) bit_array = bitarray(cadena01,endian='big') archivo.write(bit_array.tobytes()) archivo.seek(0) archivo.close() except: print "Error al escribir en "+nombre_archivo return archivo_abierto
def dynamic_optimized(weights, values, capacity): """ """ import bitarray table = [[{'value': 0, 'pre':bitarray.bitarray()} for y in range(2)] for x in xrange(0,capacity+1)] for j in range(len(weights)): for i in xrange(capacity+1): if j == 0 and i >= weights[j]: table[i][j&1] = {'value':values[j],'pre':bitarray.bitarray(1)} continue if (i >= weights[j]): if (table[i-weights[j]][~j&1]['value'] + values[j] > table[i][~j&1]['value']): table[i][j&1] = {'value':table[i-weights[j]][~j&1]['value'] + values[j], 'pre': bitarray.bitarray(table[i-weights[j]][~j&1]['pre'])} table[i][j&1]['pre'].append(1) else: table[i][j&1] = {'value':table[i][~j&1]['value'], 'pre': bitarray.bitarray(table[i][~j&1]['pre'])} table[i][j&1]['pre'].append(0) else: table[i][j&1] = {'value':table[i][~j&1]['value'], 'pre': bitarray.bitarray(table[i][~j&1]['pre'])} table[i][j&1]['pre'].append(0) maxj = max(enumerate(table[capacity]), key=lambda x: x[1]['value'])[0] taken = [[0,1][x] for x in table[capacity][maxj]['pre'].tolist()] weight = sum([weights[i] if ex else 0 for i,ex in enumerate(taken)]) value = table[capacity][maxj]['value'] return (value, weight, taken)
def __read__(self, fname, m, n): if not fname.endswith('.bed'): raise ValueError('.bed filename must end in .bed') fh = open(fname,'rb') magicNumber = ba.bitarray(endian="little") magicNumber.fromfile(fh, 2) bedMode = ba.bitarray(endian="little") bedMode.fromfile(fh, 1) ### TODO this is ugly e = (4 - n % 4) if n % 4 != 0 else 0 nru = n + e self.nru = nru # check magic number if magicNumber != ba.bitarray('0011011011011000'): raise IOError("Magic number from Plink .bed file not recognized") if bedMode != ba.bitarray('10000000'): raise IOError("Plink .bed file must be in default SNP-major mode") # check file length self.geno = ba.bitarray(endian="little") self.geno.fromfile(fh) self.__test_length__(self.geno,self.m,self.nru) return (self.nru, self.geno)
def triangle_data(bits1, bits2, data, verify): """Make a triangle out of our rule-base xxxx 1xxx xxxx 01xx xxxx => 001x xxxx 0001 :param int bits1: number of bits from mt output :param int bits2: number of bits in mt state :param list[(bitarray, bitarray)] data: our rulebase :param ((bitarray, bitarray)) -> None verify: verify function """ skipped = 0 for bit in xrange(bits2): found_bits = [b for b in find_bit(data, 1, bit) if b >= bit] print "Working on bit %d/%d (skipped: %d, found: %d)" % (bit, bits2, skipped, len(found_bits)) if len(found_bits) < 1: print "skipping" skipped += 1 bitfield1 = [0] * bits1 bitfield2 = [0] * bits2 data.insert(bit, (bitarray(bitfield1), bitarray(bitfield2))) else: main_bitfield1, main_bitfield2 = data[found_bits[0]] for pos in found_bits[1:]: bitfield1, bitfield2 = data[pos] bitfield1 ^= main_bitfield1 bitfield2 ^= main_bitfield2 verify((bitfield1, bitfield2)) if not any(bitfield1): assert not any(bitfield2) data[bit], data[found_bits[0]] = data[found_bits[0]], data[bit] verify(data[bit])
def ByteToBit(byteArray): result = bitarray() for byte in byteArray: h = '{0:08b}'.format(byte) arr = bitarray(h) result.extend(arr) return result
def bindiff(bfile1,bfile2): """ compare 2 binary files and show all differing bit locations/indices, one index per line in: binary file 1, binary file 2 for bit-wise comparison. out: Optionally store the flipped-bit index [one index location per line] in a output file 'ebitlog' """ f1 = open(bfile1,'rb') f2 = open(bfile2, 'rb') a1 = bitarray() a2 = bitarray() a1.fromfile(f1) a2.fromfile(f2) f1.close() f2.close() assert a1.length() == a2.length() n_bits = a1.length() # if FileOut: # outf= open('ebitlog','w') for i in xrange(n_bits): if a1[i] != a2[i]: print 'bit mismatch at index: ',i # if FileOut: # print >>outf, 'bit mismatch at index: ',i else: continue
def detectFrames(NRZI): # function looks for packets in an NRZI sequence and validates their checksum # compute finite differences of the digital NRZI to detect zero-crossings dNRZI = NRZI[1:] - NRZI[:-1] # find the position of the non-zero components. These are the indexes of the zero-crossings. transit = np.nonzero(dNRZI)[0] # Transition time is the difference between zero-crossings transTime = transit[1:]-transit[:-1] # loop over transitions, convert to bit streams and extract packets dict = { 1:bitarray.bitarray([0]), 2:bitarray.bitarray([1,0]), 3:bitarray.bitarray([1,1,0]), 4:bitarray.bitarray([1,1,1,0]),5:bitarray.bitarray([1,1,1,1,0]),6:bitarray.bitarray([1,1,1,1,1,0]) ,7:bitarray.bitarray([1,1,1,1,1,1,0])} state = 0; # no flag detected yet packets =[] tmppkt = bitarray.bitarray([0]) lastFlag = 0 # position of the last flag found. for n in range(0,len(transTime)): Nb = round(transTime[n]/36.75) # maps intervals to bits. Assume 44100Hz and 1200baud if (Nb == 7 and state ==0): # detected flag frame, start collecting a packet tmppkt = tmppkt + dict[7] state = 1 # packet detected lastFlag = transit[n-1] continue if (Nb == 7 and state == 1): # detected end frame successfully tmppkt = tmppkt + dict[7] # validate checksum bitsu = ax25.bit_unstuff(tmppkt[8:-8]) # unstuff bits if (genfcs(bitsu[:-16]).tobytes() == bitsu[-16:].tobytes()) : # valid packet packets.append(tmppkt) tmppkt = bitarray.bitarray([0]) state = 0 continue if (state == 1 and Nb < 7 and Nb > 0): # valid bits tmppkt = tmppkt + dict[Nb] continue else: # not valid bits reset state = 0 tmppkt = bitarray.bitarray([0]) continue if state == 0: lastFlag = -1 # if the state is 1, which means that we detected a packet, but the buffer ended, then # we return the position of the beginning of the flag within the buffer to let the caller # know that there's a packet that overlapps between two buffer frames. return packets, lastFlag
def testUpdateArrivialToOneReq(self): """Arrival of an update on a former lookup request will generate only one hit""" for i in range(self.tlbSize): #create request address = bitarray(decimalToBinaryString(i)) req = Request(address, i) #create update for the request transltedAddress = bitarray(address) transltedAddress.invert() updateReq = Request(transltedAddress, i) #send a lookup request self.dut.lookup(req) #send update request w\ translated address isHit, hitsList = self.dut.update(updateReq) self.assertTrue(isHit, "expecting a Hit for a request #%d %s" \ %(i, repr(req))) self.assertEqual( len(hitsList), 1, "hit list length is %d " \ "when 1 is expected" % ( len(hitsList))) genHit = hitsList[0] self.assertEqual(genHit, updateReq, "reported hit %s differs "\ "from update %s" % ( repr(genHit), repr(req)))
def load_window(size, document_id, user_id): size +=1 if user_id in users: a = users.index(user_id) if document_id in dictionary: dictionary[document_id][a] = 1 # print "Update!" else: dictionary[document_id] = bitarray([False] * (size - 1)) dictionary[document_id][a] = 1 # print "New!" else: users.append(user_id) updated = False for key in dictionary: if key == document_id: dictionary[key].extend([True]) updated = True else: dictionary[key].extend([False]) if not updated: dictionary[document_id] = bitarray([False] * (size - 1)) dictionary[document_id].extend([True])
def slide_window(size, document_id, user_id): # import pdb; pdb.set_trace() if user_id in users: i = users.index(user_id) if document_id in dictionary: dictionary[document_id][i] = 1 # print "Update!" else: dictionary[document_id] = bitarray([False] * (size)) dictionary[document_id][i] = 1 # print "New!" else: updated = False # print "else" del users[0] users.append(user_id) for key in dictionary.keys(): del dictionary[key][0] if key == document_id: dictionary[key].extend([True]) updated = True else: if dictionary[key].count() == 0: del dictionary[key] else: dictionary[key].extend([False]) if not updated: dictionary[document_id] = bitarray([False] * (size - 1)) dictionary[document_id].extend([True])
def test_setitem__smaller_val(self): ba = bitarray('1001010111', endian='little') bv = BitAwareByteArray(self._bitarray_to_bytes(ba), stop=float(ba.length()) / 8) val = bitarray('10', endian='little') ba[3:7] = val bv[3.0 / 8:7.0 / 8] = BitView(self._bitarray_to_bytes(val), stop=2.0 / 8) self.assertEqualBitArrayBitView(ba, bv)
def sieve_of_eratosthenes(n): if n == 2: return [2] prime_nums = bitarray(n-1) prime_nums.setall(False) p = 2 # initialize p to smallest prime while p < n: # put a 1 in indexes that are multiples of p for i in range(p + 1, n + 1): if i % p == 0: prime_nums[i-2] = bitarray('1') if prime_nums[n-2] == 1: break # set p to next prime for i in range(p + 1, n + 1): if prime_nums[i-2] == 0: p = i break ans = [] for i in range(0, n-1): if prime_nums[i] == 0: ans.append(i+2) return ans
def update_node(self, node, distribution): dt = np.copy(distribution) if node.mask is not None: dt[node.mask] = 0.0 if self.pb.omp_threads == 1: val, bout = self.single_thread(dt) else: val, bout = self.multi_thread(dt) if mpi4py.__version__.split('.')[0] > 1: new = self.pb.comm.allreduce((val[0], self.pb.rank), MPI.MINLOC) else: new = self.pb.comm.allreduce(val[0], None, MPI.MINLOC) val = self.pb.comm.bcast(val, root=new[1]) bout_ba = bitarray(list(bout)) bout_c = bout_ba.tobytes() bout_c = self.pb.comm.bcast(bout_c, root=new[1]) bout_ba = bitarray() bout_ba.frombytes(bytes(bout_c)) bout = np.array(bout_ba.tolist()[0:self.pb.total_exam_no]) (rnk, d1, d2, d3, d4, d5, c0, c1) = val[1:9] rnk = int(rnk) node.rnk = rnk node.d1 = d1 node.d2 = d2 node.d3 = d3 node.d4 = d4 node.d5 = d5 node.c0 = c0 node.c1 = c1 node.set_pred(pred=bout) return node
def decode(msgimg,img): #import images img1 = cv2.imread(msgimg) img2 = cv2.imread(img) #get end of message key key = ba.bitarray() key.fromstring("#00#") #start message bit array msg = ba.bitarray() shape = img1.shape for i in range(shape[0]): for j in range(shape[1]): msg.append(img1[i,j][0] - img2[i,j][0]) if contains(key,msg): return ba.bitarray(msg).tostring()[:-4] msg.append(img1[i,j][1] - img2[i,j][1]) if contains(key,msg): return ba.bitarray(msg).tostring()[:-4] msg.append(img1[i,j][2] - img2[i,j][2]) if contains(key,msg): return ba.bitarray(msg).tostring()[:-4] return "No Message in these images"
def pad(self): """ Pads a block to have k bitarrays of symbolsize * 8 bits length Arguments: k -- number of bit arrays symbolsize -- Size of each array in bytes """ bitlength = self.symbolsize * 8 for row in self: if len(row) < bitlength: self.padding += (bitlength - len(row)) / 8 extension = bitarray(bitlength - len(row)) extension.setall(False) row.extend(extension) # Last provided row should be the only row that needs row padding break if len(self) < self.k: for i in xrange(len(self), self.k): padrow = bitarray(bitlength) padrow.setall(False) self.append(padrow) self.padding += bitlength / 8
def substitute(self, bits): """ This is the "heart" of the algorithm. The function applies substitution to the data according to the well defined S-boxes used in DES. :param bits: the data to substitute. :return: diffused data. """ blocks = self.chunks(bits, 6) new_bits = bitarray() for i, block in enumerate(blocks): left_outer_bit = block[0] right_outer_bit = block[5] outer_bits = bitarray([left_outer_bit, right_outer_bit]) inner_bits = block[1:4] row = bitutils.bin_to_int(outer_bits) col = bitutils.bin_to_int(inner_bits) s = DES.S[i][row][col] b = '{0:04b}'.format(s) new_bits.extend(b) return new_bits
def convert_image_to_printer_format(image): '''Takes an image and converts the data into something that the Pipsta printer recognises. ''' (width, height) = image.size area = width * height # Convert to bitarray for manipulation imagebits = bitarray(image.getdata()) # required as img has white = true (as RGB all = 255), and we are # rendering black dots # pylint: disable=E1101 imagebits.invert() printbits = bitarray(area) # This loop converts standard image orientation to single dot graphics, # populating printbits with imagebits LOGGER.debug("Starting decode to print dots (size={})".format(image.size)) for image_bit_index in range(0, area): width_times_byte_height = width << 3 width_times_bit_height = width_times_byte_height * 3 print_col = image_bit_index % width char_row = image_bit_index // width_times_bit_height print_byte = ((image_bit_index % width_times_bit_height) // (width_times_byte_height)) + (3 * print_col) print_bit = (image_bit_index % width_times_byte_height) // width print_bit_index = print_bit + (print_byte * 8) + \ (char_row * width_times_bit_height) printbits[print_bit_index] = imagebits[image_bit_index] LOGGER.debug("Done decoding!") return printbits
def signed_int2bits(self, num): if num >= 0: return bitarray('0', endian='big') + _bin(num) else: tmp = bitarray('0', endian='big') + self.unsigned_int2bits(-num) tmp.invert() return _bin(bin2int(tmp) + 1)
def get_bits_int(i): rs = reedsolo.RSCodec(RS) b1 = bitarray('{0:016b}'.format(i)) e = rs.encode(b1.tobytes()) b2 = bitarray() b2.frombytes(str(e)) return b2
def __init__(self, value, base=10): i = int(value, base=base) self._value = bitarray(f"{i:b}")
def immToInt(imm): """Converts imm bitarray into twos complement integer""" return int( RVFormatParser.twos_compliment(int(bitarray(imm).to01(), 2), len(imm)))
def convertToIntRegister(ba): """ Takes in a bitarray or string of bits and converts it into a string specifying an integer register """ return "x{}".format(util.ba2int(bitarray(ba)))
def getFunct7(ba): """ Returns the funct7 of an instruction, a funct7, like a funct3, further specifies what instruction an opcode refers to""" return bitarray(ba[:-25])
def getFunct3(ba): """ Returns the funct3 of a given instruction, a funct3 further specifies what instruction a given opcode refers to""" return bitarray(ba[-15:-12])
def NFtoInt(ba): """Converts nf bitarray into integer + 1""" return "seg{}".format(util.ba2int(bitarray(ba)) + 1)
def convertToVectorRegister(ba): """ Takes in a bitarray or string of bits and converts it into a string specifying a vector register """ return "v{}".format(util.ba2int(bitarray(ba)))
def clade_to_bitarr(self, clade): bit_list = ['0'] * self.ntaxa for i in clade: bit_list[self.map[i]] = '1' return bitarray(''.join(bit_list))
def _merge_bitarr(self, key): return bitarray(key[:self.ntaxa]) | bitarray(key[self.ntaxa:])
def numpy_array_to_bitarray(a): ba = bitarray() ba.frombytes(a.tobytes()) return ba
def traverse(nd, prefix=bitarray(0, endian)): if hasattr(nd, 'symbol'): # leaf result[nd.symbol] = prefix else: # parent, so traverse each of the children traverse(nd.child[0], prefix + bitarray([0])) traverse(nd.child[1], prefix + bitarray([1]))
def _decomp_minor_bitarr(self, key): return min(bitarray(key[:self.ntaxa]), bitarray(key[self.ntaxa:]))
def __init__(self, size, hash_count): self.size = size self.hash_count = hash_count self.bit_array = bitarray(size) self.bit_array.setall(0)
def test_rank_in_byte(b: int) -> None: bits = bitarray() bits.frombytes(bytes([b])) for i in range(len(bits)): assert RANK_IN_BYTE[256 * i + b] == sum(bits[0:(i + 1)])
temp = np.copy(sl) imgFilter(sl[0, :], filterType, previous[0, :]) previous = temp if (channelCount > 1): newScanlines = mergeScanlines(scanlines, filterType) else: newScanlines = mergeScanlinesGrey(scanlines, filterType) iDATStart = outputPNG.tell() zLibHeaderArray = bytearray([120, 1]) outputPNG.write(zLibHeaderArray) uncompressedArray = bytearray() outputBitStream = ba.bitarray(endian='little') for i in range(0, len(newScanlines)): print(str(i + 1) + '/' + str(imSize[0])) if (i != (len(newScanlines) - 1)): deflate(newScanlines[i], windowSize, outputPNG, 0, huffman, outputBitStream) uncompressedArray += bytearray(newScanlines[i]) else: deflate(newScanlines[i], windowSize, outputPNG, 1, huffman, outputBitStream) uncompressedArray += bytearray(newScanlines[i]) outputBitStream.tofile(outputPNG) adler32Value = zlib.adler32(bytearray(uncompressedArray))
def int2ba(i, length=None, endian=None, signed=False): """int2ba(int, /, length=None, endian=None, signed=False) -> bitarray Convert the given integer to a bitarray (with given endianness, and no leading (big-endian) / trailing (little-endian) zeros), unless the `length` of the bitarray is provided. An `OverflowError` is raised if the integer is not representable with the given number of bits. `signed` determines whether two's complement is used to represent the integer, and requires `length` to be provided. """ if not isinstance(i, (int, long) if _is_py2 else int): raise TypeError("int expected, got '%s'" % type(i).__name__) if length is not None: if not isinstance(length, int): raise TypeError("int expected for length") if length <= 0: raise ValueError("integer larger than 0 expected for length") if signed and length is None: raise TypeError("signed requires length") if i == 0: # there are special cases for 0 which we'd rather not deal with below return zeros(length or 1, endian) if signed: m = 1 << (length - 1) if not (-m <= i < m): raise OverflowError("signed integer not in range(%d, %d), " "got %d" % (-m, m, i)) if i < 0: i += 1 << length else: # unsigned if i < 0: raise OverflowError("unsigned integer not positive, got %d" % i) if length and i >= (1 << length): raise OverflowError("unsigned integer not in range(0, %d), " "got %d" % (1 << length, i)) a = bitarray(0, get_default_endian() if endian is None else endian) big_endian = bool(a.endian() == 'big') if _is_py2: c = bytearray() while i: i, r = divmod(i, 256) c.append(r) if big_endian: c.reverse() b = bytes(c) else: # py3 b = i.to_bytes(bits2bytes(i.bit_length()), byteorder=a.endian()) a.frombytes(b) if length is None: return strip(a, 'left' if big_endian else 'right') la = len(a) if la > length: a = a[-length:] if big_endian else a[:length] if la < length: pad = zeros(length - la, endian) a = pad + a if big_endian else a + pad assert len(a) == length return a
def extract_bit_array(m_string): """Extract the bit array(list) of message without encoding""" bitarray_ = bitarray.bitarray() bitarray_.frombytes(m_string.encode('utf-8')) return [int(i) for i in bitarray_]
def deflate(scanline, searchWindowL, outputPNG, isLast, huffman, outputBitStream): startLoc = outputPNG.tell() #Prva tri bita svakog bloka if (isLast != 1): outputBitStream += ba.bitarray('010') else: outputBitStream += ba.bitarray('110') resultArray = np.uint16(scanline[0]) searchBuffer = [scanline[0]] outputBitStream += ba.bitarray(getHuffman(scanline[0], huffman)) i = 1 n = len(scanline) while (i < n): #Start index Is = i - searchWindowL if (Is < 0): Is = 0 #End Index Ie = n searchBuffer = list(scanline[Is:(i)]) aheadBuffer = list(scanline[i:Ie]) startSearchLen = len(searchBuffer) #Prvi element searchedEle = [aheadBuffer[0]] ELV = findInWindow(searchedEle, searchBuffer, startSearchLen) if ELV[0]: searchBuffer.append(searchedEle[0]) num_br = 1 endOfRow = 0 # Trazim dok god imam brojeva u bufferu if len(aheadBuffer) > num_br: newSearch = searchedEle n_ex = ELV[0] while n_ex == 1: num_br += 1 if (num_br <= len(aheadBuffer)): newSearch.append(aheadBuffer[num_br - 1]) nELV = findInWindow(newSearch, searchBuffer, startSearchLen) n_ex = nELV[0] if (nELV[2] == 256): break if (nELV[0] == 1): searchBuffer.append(aheadBuffer[num_br - 1]) else: endOfRow = 1 if (nELV[0] == 1): searchBuffer.pop() break if (num_br > 1 and endOfRow == 0): num_br -= 1 searchBuffer = searchBuffer[:len(searchBuffer) - 1] # Ako je postojao pre if (ELV[0] == 1): newEle = aheadBuffer[0:num_br] rELV = findInWindow(newEle, searchBuffer[0:len(searchBuffer)], startSearchLen) if (rELV[2] > 2): i += rELV[2] outputBitStream += ba.bitarray(getLenCode(rELV[2], huffman)) outputBitStream += ba.bitarray(getDistCode(rELV[1])) else: i += rELV[2] if (rELV[2] == 1): outputBitStream += ba.bitarray( getHuffman(aheadBuffer[0], huffman)) else: outputBitStream += ba.bitarray( getHuffman(aheadBuffer[0], huffman)) outputBitStream += ba.bitarray( getHuffman(aheadBuffer[1], huffman)) else: #Ako nije i += 1 outputBitStream += ba.bitarray( getHuffman(int(searchedEle[0]), huffman)) #Oznaka kraja bloka outputBitStream += ba.bitarray(getHuffman(256, huffman)) endLoc = outputPNG.tell() return endLoc - startLoc
def __init__(self): self.bits = bitarray()
seq_size = 128 # granularity of the clock sequencer dut['SMU3'].off() dut['SMU3'].source_volt() dut['SMU3'].set_voltage_range(1.5) dut['SMU3'].set_current_nlpc(10) dut['SMU3'].set_voltage(1.0) dut['SMU3'].set_current_limit(0.001) dut['SMU3'].set_current_sense_range(0.00001) m = seq_size/2 - 1 # define index of the last 1 in order to create a non-overlapping clock sequence cnt = seq_size/2 - 1 # counter for numbering in output file table_row = [] # create initial bit arrays for a given sequencer size bit_array_CLK_3 = bitarray(seq_size) bit_array_CLK_3.setall(0) bit_array_CLK_3[1:m] = 1 bit_array_CLK_0 = bitarray(seq_size) bit_array_CLK_0.setall(0) bit_array_CLK_0[m+1:-1] = 1 # vary charging time by looping over the number of bits in bit_array_CLK_3 that are set to 1; number is reduced by one in every step for i in range(m , 0 , -1): dut['SEQ'].reset() dut['SEQ'].set_clk_divide(1) dut['SEQ'].set_repeat_start(0) dut['SEQ'].set_repeat(0) dut['SEQ'].set_size(seq_size)
#!/usr/bin/env python3 """Docstring""" import sys from math import ceil from bitarray import bitarray import reedsolo BARKER = bitarray('1111100110101') RS_CODEC_32 = reedsolo.RSCodec(4) RS_CODEC_128 = reedsolo.RSCodec(16) def main(): """Docstring""" # SETUP # # Get the content from pipe, strip trailing whitespace stdin_content = ''.join(line for line in sys.stdin).rstrip() # Will hold BFSK data bfsk = bitarray() # HEADER # # Add 13-bit Barker code bfsk.extend(BARKER) # Add content length in bytes, encoded using Reed-Solomon clib = len(stdin_content).to_bytes(2, byteorder='big') rs_clib = RS_CODEC_32.encode(clib) rs_clib_str = ''.join('{0:08b}'.format(byte) for byte in rs_clib) bfsk.extend(rs_clib_str) # DATA #
def __init__(self, max_count, order=1): self.max_count = max_count self.allocation_order = order self.index_allocator = bitarray([0]*max_count)
def main(): try: opts, args = getopt.getopt(sys.argv[1:], "k", ["keepfiles"]) except getopt.GetoptError as e: print str(e) sys.exit(127) k = False for o, a in opts: if o in ["-k", "--keepfiles"]: k = True pyangpath = os.environ.get('PYANGPATH') if os.environ.get( 'PYANGPATH') is not None else False pyangbindpath = os.environ.get('PYANGBINDPATH') if os.environ.get( 'PYANGBINDPATH') is not None else False assert not pyangpath == False, "could not find path to pyang" assert not pyangbindpath == False, "could not resolve pyangbind directory" this_dir = os.path.dirname(os.path.realpath(__file__)) os.system("%s --plugindir %s -f pybind -o %s/bindings.py %s/%s.yang" % (pyangpath, pyangbindpath, this_dir, this_dir, TESTNAME)) from bindings import serialise_json js = serialise_json() js.c1.l1.add(1) for s in ["int", "uint"]: for l in [8, 16, 32, 64]: name = "%s%s" % (s, l) x = getattr(js.c1.l1[1], "_set_%s" % name) x(1) js.c1.l1[1].restricted_integer = 6 js.c1.l1[1].string = "bear" js.c1.l1[1].restricted_string = "aardvark" js.c1.l1[1].union = 16 js.c1.l1[1].union_list.append(16) js.c1.l1[1].union_list.append("chicken") js.c1.t1.add(16) js.c1.l1[1].leafref = 16 from bitarray import bitarray js.c1.l1[1].binary = bitarray("010101") js.c1.l1[1].boolean = True js.c1.l1[1].enumeration = "one" js.c1.l1[1].identityref = "idone" js.c1.l1[1].typedef_one = "test" js.c1.l1[1].typedef_two = 8 js.c1.l1[1].one_leaf = "hi" print js.get() for i in range(1, 10): js.c1.l2.add(i) print json.dumps(js.get(), cls=pybindJSONEncoder, indent=4) # from ocbindings import bgp # from lib.xpathhelper import YANGPathHelper # ph = YANGPathHelper() # ocbgp = bgp(path_helper=ph) # add_peers = [ # ("192.168.1.1", "2856", "linx-peers"), # ("172.16.12.2", "3356", "transit"), # ("10.0.0.3", "5400", "private-peers"), # ("10.0.0.4", "3300", "private-peers"), # ("192.168.1.2", "6871", "linx-peers") # ] # for e in add_peers: # if not e[2] in ocbgp.bgp.peer_groups.peer_group: # ocbgp.bgp.peer_groups.peer_group.add(e[2]) # if not e[0] in ocbgp.bgp.neighbors.neighbor: # ocbgp.bgp.neighbors.neighbor.add(e[0]) # ocbgp.bgp.neighbors.neighbor[e[0]].config.peer_group = e[2] # ocbgp.bgp.neighbors.neighbor[e[0]].config.peer_type = "EXTERNAL" # ocbgp.bgp.neighbors.neighbor[e[0]].config.send_community = "STANDARD" # ocbgp.bgp.neighbors.neighbor[e[0]].route_reflector.config.route_reflector_client = True # ocbgp.bgp.neighbors.neighbor[e[0]].route_reflector.config.route_reflector_cluster_id = "192.168.1.1" # #ocbgp.bgp.neighbors.neighbor.add("42.42.42.42") # #ocbgp.bgp.neighbors.neighbor["42.42.42.42"].config.peer_group = "DOES NOT EXIST!" # print ocbgp.bgp.peer_groups.get(filter=True) # print json.dumps(ocbgp.get(), cls=pybindJSONEncoder, indent=4) if not k: os.system("/bin/rm %s/bindings.py" % this_dir) os.system("/bin/rm %s/bindings.pyc" % this_dir)
def read_bitarray(self, bits): """ Read 'bits' bits returning the value as a :py:class:`bitarray.bitarray`. """ return bitarray(self.read_bit() for _ in range(bits))
def hex2ba(s, endian=None): a = bitarray(0, endian or get_default_endian()) a.encode(CODEDICT[a.endian()], s) return a
from bitarray import bitarray import sounddevice as sd import values a = HuffmanCode() encode = a.compress("test.txt") b = Transmitter(encode) chunks = b.chunks packet = b.encode() final_packet = [] for p in packet: check = Pack(p) final_packet.append(check.get_final_packet()) bits = "" for p in final_packet: print(p) bits += p print("sending") transmit(bitarray(bits), baud=values.baud, signal_cf=values.sig_cf, clock_cf=values.clock_cf, fdev=values.delta, fs=values.fs, packet_size=32) sd.wait()
def test_simple(self): self.assertRaises(TypeError, strip, '0110') self.assertRaises(TypeError, strip, bitarray(), 123) self.assertRaises(ValueError, strip, bitarray(), 'up') for default_endian in 'big', 'little': _set_default_endian(default_endian) a = bitarray('00010110000') self.assertEQUAL(strip(a), bitarray('0001011')) self.assertEQUAL(strip(a, 'left'), bitarray('10110000')) self.assertEQUAL(strip(a, 'both'), bitarray('1011')) b = frozenbitarray('00010110000') self.assertEqual(strip(b, 'both'), bitarray('1011')) for mode in 'left', 'right', 'both': self.assertEqual(strip(bitarray('000'), mode), bitarray()) self.assertEqual(strip(bitarray(), mode), bitarray())
def test_empty(self): a = bitarray(endian='little') b = make_endian(a, 'big') self.assertTrue(b == a) self.assertEqual(len(b), 0) self.assertEqual(b.endian(), 'big')
self.assertTrue(subset(a, b)) # but b in not always a subset of a self.assertEqual(subset(b, a), self.subset_simple(b, a)) # we set all bits in a, which ensures that b is a subset of a a.setall(1) self.assertTrue(subset(b, a)) tests.append(TestsSubset) # --------------------------------------------------------------------------- CODEDICT = { 'little': {}, 'big': { '0': bitarray('0000'), '1': bitarray('0001'), '2': bitarray('0010'), '3': bitarray('0011'), '4': bitarray('0100'), '5': bitarray('0101'), '6': bitarray('0110'), '7': bitarray('0111'), '8': bitarray('1000'), '9': bitarray('1001'), 'a': bitarray('1010'), 'b': bitarray('1011'), 'c': bitarray('1100'), 'd': bitarray('1101'), 'e': bitarray('1110'), 'f': bitarray('1111'),
def test_False(self): for a, b in [('1', '0'), ('1101', '0111'), ('0000101111', '0100111011')]: a, b = bitarray(a), bitarray(b) self.assertTrue(subset(a, b) is False) self.assertTrue(self.subset_simple(a, b) is False)