def booth(m, r): x = 8 y = 8 totallength = x + y + 1 mA = BitArray(int=m, length=totallength) rA = BitArray(int=r, length=totallength) A = mA << (y + 1) S = BitArray(int=-m, length=totallength) << (y + 1) P = BitArray(int=r, length=y) P.prepend(BitArray(int=0, length=x)) P = P << 1 print "Initial values" print "", A.bin print "", S.bin print "", P.bin for i in range(1, y + 1): if P[-2:] == '0b01': P = BitArray(int=P.int + A.int, length=totallength) print "P + A:", P.bin elif P[-2:] == '0b10': P = BitArray(int=P.int + S.int, length=totallength) print "P + S:", P.bin P = arith_shift_right(P, 1) print "P >> 1:", P.bin P = arith_shift_right(P, 1) print "P >> 1:", P.bin return P.int
def huff_encode(text): freq = defaultdict(int) for s in text: freq[s] += 1 tree = [ [f, [s, ""]] for s,f in freq.items() ] heapify(tree) while len(tree) > 1: l = heappop(tree) h = heappop(tree) for n in l[1:]: n[1] = '0' + n[1] for n in h[1:]: n[1] = '1' + n[1] heappush(tree, [l[0] + h[0]] + l[1:] + h[1:]) root = heappop(tree)[1:] codes = dict([(s, "0b"+c) for s,c in root]) # Header enc = BitArray() for s,c in root: enc += BitArray(bytes=s) enc += BitArray(uint=len(c), length=8) enc += BitArray("0b"+c) enc.prepend(BitArray(uint=len(root), length=8)) for s in text: enc += BitArray(codes[s]) return enc
def multiply_bins(m, r, x, y): #Алгоритм Бута print(m," x ",r) length = x + y + 1 m_arr = BitArray(int = m, length = length) A = m_arr<<(y+1) #Заповнити найбільш значимі (з ліва) біти значенням m. Біти (y + 1), які залишилися, заповнити нулями. print("A = ", A.bin) S = BitArray(int = -m, length = length) << (y+1) #Заповнити найбільш значимі біти значенням (−m) в додатковому коді. Біти (y + 1), які залишилися, заповнити нулями. print("S = ", S.bin) P = BitArray(int = r, length = y) #заповнити біти значенням r. P.prepend(BitArray(int = 0, length = x)) #Заповнити найбільш значимі x біт нулями. P = P << 1 #Записати 0 в крайній найменший значимий (правий) біт. print("P = ", P.bin) for _ in range(1, y + 1): if P[-2:] == '0b01': #if last two bits are 01, find P+A P = BitArray(int = P.int + A.int, length = length) print("P + A = ", P.bin) elif P[-2:] == '0b10': #if last two bits are 10, find P+S P = BitArray(int = P.int + S.int, length = length) print("P + S = ", P.bin) P = ar_shift(P, 1) #Виконати операцію арифметичного зсуву над значенням, яке було отримане на другому кроці, на один біт вправо. Присвоїти P це нове значення. print("P >> 1 = ", P.bin) P = ar_shift(P, 1) #Відкинути крайній найменш значимий (правий) біт P. Це і є добуток m і r. print("P >> 1 = ", P.bin) return P.int
def booth(m, r): x=8 y=8 # Initialize totalLength = x + y + 1 mA = BitArray(int = m, length = totalLength) #2 00000000000000010 rA = BitArray(int = r, length = totalLength) A = mA << (y+1)#2 = 00000010000000000# S = BitArray(int = -m, length = totalLength) << (y+1)#subtractor P = BitArray(int = r, length = y) P.prepend(BitArray(int = 0, length = x))#this is Q in AQQ-1 P = P << 1 print "Initial values" print "A", A.bin print "S", S.bin print "P", P.bin print "Starting calculation" for i in range(1,y+1): if P[-2:] == '0b01': P = BitArray(int = P.int + A.int, length = totalLength) print "P + A:", P.bin elif P[-2:] == '0b10': P = BitArray(int = P.int +S.int, length = totalLength)#a=a-m print "P + S:", P.bin P = arith_shift_right(P, 1) print "P >> 1:", P.bin P = arith_shift_right(P, 1) print "P >> 1:", P.bin return P.int
def booth(m, r, x, y): # Initialize totalLength = x + y + 1 mA = BitArray(int = m, length = totalLength) rA = BitArray(int = r, length = totalLength) A = mA << (y+1) S = BitArray(int = -m, length = totalLength) << (y+1) P = BitArray(int = r, length = y) P.prepend(BitArray(int = 0, length = x)) P = P << 1 print "Initial values" print "A", A.bin print "S", S.bin print "P", P.bin print "Starting calculation" for i in range(1,y+1): if P[-2:] == '0b01': P = BitArray(int = P.int + A.int, length = totalLength) print "P + A:", P.bin elif P[-2:] == '0b10': P = BitArray(int = P.int +S.int, length = totalLength) print "P + S:", P.bin P = arith_shift_right(P, 1) print "P >> 1:", P.bin P = arith_shift_right(P, 1) print "P >> 1:", P.bin return P.int
def hf_compress(byte_array): MAX_SIZE = 256 freq_table = [0 for i in range(MAX_SIZE)] for b in byte_array: freq_table[b] += 1 hf_tree = create_huffman_tree(freq_table) hf_codes = parse_tree(hf_tree) result = BitArray(bin_pad(len(hf_codes), 8)) for n in hf_codes: byte_key = bytes([n[0]]) result.append(byte_key) code_length = bin_pad(len(n[1]), 4) result.append(code_length) result.append('0b' + n[1]) for b in byte_array: code = [c[1] for c in hf_codes if c[0] == b].pop() result.append('0b' + code) # find required padding to make bits go into bytes padding_size = 8 - len(result.bin) % 8 result.prepend(bin_pad(padding_size, 8)) return result.tobytes()
def booth(m, r, x, y): # starting booths logic totalLength = x + y + 1 mA = BitArray( int=m, length=totalLength ) # convert 1st no (int data) into binary and store it in mA with total length of 17 bits (16+carry) print(mA) A = mA << (y + 1) # left shift mA by 1 bit print(A) mA1 = BitArray( int=-m, length=totalLength ) # convert 2nd no (int data) into binary and store it in mA1 with total length of 17 bits (16+carry) S = mA1 << (y + 1) # left shift mA1 by 1 bit P1 = BitArray( int=r, length=y ) # convert 2nd no (int data) into binary and store it in p1 with total length of 8 bits (as y=8) P1.prepend( BitArray(int=0, length=x) ) # pre-append converted 1st no (int data) into binary at p1. now p1 is of 16 bits. P = P1 << (1) # left shitf operation on p1 and store it in p print("A : ", A.bin) #print binary of A print("S : ", S.bin) #print binary of S for i in range(1, y + 1): # check for -ve sign in input and output. if P[-2:] == '0b01': # 1st no contains -ve sign then ans also contain -ve sign P = BitArray(int=P.int + A.int, length=totalLength) # add -ve sign to answer elif P[-2:] == '0b10': # 2nd no contains -ve sign then ans also contain -ve sign P = BitArray(int=P.int + S.int, length=totalLength) # add -ve sign to answer P = BitArray(int=(P.int >> 1), length=P.len) # convert answer into binary and int. P = P[:-1] print("P : ", P.bin) # print binary i=on terminal return P.bin, P.int # print binary + integer on web page
def testPrependAfterCreationFromDataWithOffset(self): s1 = BitArray(bytes=b'\x00\x00\x07\xff\xf0\x00', offset=21, length=15) self.assertFalse(s1.any(0)) s1.prepend('0b0') self.assertEqual(s1.bin, '0111111111111111') s1.prepend('0b0') self.assertEqual(s1.bin, '00111111111111111')
def booth(m, r, x, y): # Initialize totalLength = x + y + 1 mA = BitArray(int = m, length = totalLength) A = mA << (y+1) S = BitArray(int = -m, length = totalLength) << (y+1) P = BitArray(int = r, length = y) P.prepend(BitArray(int = 0, length = x)) P = P << 1 print "Initial values" print "A", A.bin print "S", S.bin print "P", P.bin print "Starting calculation" for i in range(1,y+1): if P[-2:] == '0b01': P = BitArray(int = P.int + A.int, length = totalLength) print "P + A:", P.bin elif P[-2:] == '0b10': P = BitArray(int = P.int +S.int, length = totalLength) print "P + S:", P.bin P = arith_shift_right(P, 1) print "P >> 1:", P.bin P = arith_shift_right(P, 1) print "P >> 1:", P.bin return P.int
def booth(m, r, x, y): total_length = x + y + 1 mA = BitArray(int=m, length=total_length) print mA A = mA << (y + 1) print A mA1 = BitArray(int=-m, length=total_length) print mA1 S = mA1 << (y + 1) print S P1 = BitArray(int=r, length=y) P1.prepend(BitArray(int=0, length=x)) P = P1 << (1) print "A:", A.bin print "S:", S.bin for i in range(1, y + 1): if P[-2:] == "0b01": P = BitArray(int=P.int + A.int, length=total_length) if P[-2:] == "0b10": P = BitArray(int=P.int + S.int, length=total_length) P = BitArray(int=(P.int >> (1)), length=total_length) P = P[:-1] print "P:", P.bin return P.bin, P.int
def bit_add32(bs1, bs2): b1 = int(bs1.bin, 2) b2 = int(bs2.bin, 2) b3 = b1 + b2 bs3 = BitArray(bin(b3)) while len(bs3) < 32: bs3.prepend('0x0') return bs3[-32:]
def array2hexstring(array, dtype, pad_to_nbits, prefix="0x", reverse=False): """ Pack given one-dimensional NumPy array with FINN DataType dtype into a hex string. Any BIPOLAR values will be converted to a single bit with a 0 representing -1. pad_to_nbits is used to prepend leading zeros to ensure packed strings of fixed width. The minimum value for pad_to_nbits is 4, since a single hex digit is four bits. reverse can be used to reverse the array prior to packing. Examples: array2hexstring([1, 1, 1, 0], DataType.BINARY, 4) = "0xe" array2hexstring([1, 1, 1, 0], DataType.BINARY, 8) = "0x0e" array2hexstring([1, 1, 0, 1], DataType.BINARY, 4, reverse=True) = "0xb" array2hexstring([1, 1, 1, 0], DataType.BINARY, 8, reverse=True) = "0x07" """ if pad_to_nbits < 4: pad_to_nbits = 4 # ensure input is a numpy array with float values if type(array) != np.ndarray or array.dtype != np.float32: # try to convert to a float numpy array (container dtype is float) array = np.asarray(array, dtype=np.float32) # ensure one-dimensional array to pack assert array.ndim == 1, "The given array is not one-dimensional." if dtype == DataType.BIPOLAR: # convert bipolar values to binary array = (array + 1) / 2 dtype = DataType.BINARY # reverse prior to packing, if desired if reverse: array = np.flip(array, -1) lineval = BitArray(length=0) bw = dtype.bitwidth() for val in array: # ensure that this value is permitted by chosen dtype assert dtype.allowed( val), "This value is not permitted by chosen dtype." if dtype.is_integer(): if dtype.signed(): lineval.append(BitArray(int=int(val), length=bw)) else: lineval.append(BitArray(uint=int(val), length=bw)) else: lineval.append(BitArray(float=val, length=bw)) if pad_to_nbits >= lineval.len: # extend to the desired output width (a minimum of 4 bits) lineval.prepend(BitArray(length=pad_to_nbits - lineval.len)) else: raise Exception("Number of bits is greater than pad_to_nbits") # represent as hex return prefix + lineval.hex
def _root_path(self): code = BitArray() node = self while not node._is_root(): if node._is_left_child(): code.prepend('0b0') else: code.prepend('0b1') node = node.p return code
def rc(t): if t % 255 == 0: return True r = BitArray('0b10000000') for i in range(1, t%255 + 1): r.prepend('0b0') # A especificacao do NIST diz para fazer uma soma de bits. # Essa operacao em um bit, eh exatamente equivalente ao XOR r[0] = (r[0] ^ r[8]) r[4] = (r[4] ^ r[8]) r[5] = (r[5] ^ r[8]) r[6] = (r[6] ^ r[8]) r = r[:8] return r[0]
def rc(t): if t % 255 == 0: return True r = BitArray('0b10000000') for i in range(1, t % 255 + 1): r.prepend('0b0') # A especificacao do NIST diz para fazer uma soma de bits. # Essa operacao em um bit, eh exatamente equivalente ao XOR r[0] = (r[0] ^ r[8]) r[4] = (r[4] ^ r[8]) r[5] = (r[5] ^ r[8]) r[6] = (r[6] ^ r[8]) r = r[:8] return r[0]
def rc(self, t): if t % 255 == 0: return 1 R = BitArray(bin='10000000') for i in range(1, t%255 + 1): R.prepend('0b0') R[0] = (R[0] + R[8]) % 2 R[4] = (R[4] + R[8]) % 2 R[5] = (R[5] + R[8]) % 2 R[6] = (R[6] + R[8]) % 2 R = R[:8] return R[0]
def to_bytearray(self): ba = bytearray(self.block_size - self.num_bytes_for_pointers) pointers = BitArray() offset = -1 for i in range(0, self.max_num_records): if self.records[i] is None: offset = -1 else: ba[i * RECORD_SIZE:(i + 1) * RECORD_SIZE] = self.records[i].to_bytearray() offset = i * RECORD_SIZE pointers.prepend( BitArray( bin=np.binary_repr(offset, width=self.addr_bit_width))) padded_pointers = pad_bits(pointers, self.num_bytes_for_pointers).bytes diff = self.block_size - len(ba) - len(padded_pointers) return ba + bytearray(diff) + padded_pointers
def booth(m, r, x, y): tot = x + y + 1 mA = BitArray(int=m, length=tot) print mA A = mA << (y + 1) mA1 = BitArray(int=-m, length=tot) B = mA1 << (y + 1) P = BitArray(int=r, length=x) P.prepend(BitArray(int=0, length=y)) P = P << (1) for i in range(0, y): if (P[-2:] == '0b01'): P = BitArray(int=P.int + A.int, length=tot) elif (P[-2:] == '0b10'): P = BitArray(int=P.int + B.int, length=tot) P = BitArray(int=P.int >> (1), length=tot) P = P[:-1] return P.bin, P.int
def booth(multiplicand, multiplier, x, y): totalLength = x + y + 1 M1 = BitArray(int=multiplicand, length=totalLength) A = M1 << (y + 1) M2 = BitArray(int=-multiplicand, length=totalLength) S = M2 << (y + 1) print "value of S " + str(S.int) P1 = BitArray(int=multiplier, length=y) P1.prepend(BitArray(int=0, length=x)) P = P1 << (1) for i in range(1, y + 1): if P[-2:] == '0b01': P = BitArray(int=P.int + A.int, length=totalLength) elif P[-2:] == '0b10': P = BitArray(int=P.int + S.int, length=totalLength) P = BitArray(int=(P.int >> 1), length=P.len) P = P[:-1] return P.bin, P.int
def hash(self, key): """ Key should be two tuple, where the first item is the key for jenkins hash while the second part is only xored to the first part. :param key: input data to be hashed divided into two parts. :type key: tuple(int, int) :returns: Hash value. :rtype: int """ h1 = jenkins.hash(self, key[0]) h1_data = BitArray(uint=h1, length=32) # h2_data = BitArray(bytes=key[1]) h2_data = BitArray(bytes=key[1]) h2_data.prepend(BitArray(uint=0, length=32 - (len(h2_data)))) #h = h1^key[1]; h3 = h1_data ^ h2_data #print(h1_data.hex,h2_data.hex,h3.hex) #print(h3.uint &0x00000FFF) return h3.uint #& 0x000007FF;
class GifDataStream: def __init__(self, bytez): self.bytez = bytearray(bytez) self.remainder = BitArray() def read_uint(self, n): while len(self.remainder) < n: self.remainder.prepend(Bits(bytearray([self.bytez.pop(0)]))) uint = self.remainder.uint & (2**n - 1) self.remainder >>= n del self.remainder[0:n] return uint def peek_uint(self, n): s = self.remainder.copy() i = 0 while len(s) < n: s.prepend(Bits(bytearray(self.bytez[i:i + 1]))) i += 1 bits = Bits(s) return bits.uint & (2**n - 1)
def booth(m, r, x, y): totalLength = x + y + 1 mA = BitArray(int=m, length=totalLength) A = mA << (y + 1) mA1 = BitArray(int=-m, length=totalLength) S = mA1 << (y + 1) P1 = BitArray(int=r, length=y) P1.prepend(BitArray(int=0, length=x)) P = P1 << (1) print "A : ", A.bin print "S : ", S.bin for i in range(1, y + 1): if P[-2:] == '0b01': P = BitArray(int=P.int + A.int, length=totalLength) elif P[-2:] == '0b10': P = BitArray(int=P.int + S.int, length=totalLength) P = BitArray(int=(P.int >> 1), length=P.len) P = P[:-1] print "P : ", P.bin return P.bin, P.int
def booths(num1, num2, len): totalLength = len + len + 1 mulArray = BitArray(int=num1, length=totalLength) compMulArray = BitArray(int=-num1, length=totalLength) add = mulArray << (len + 1) sub = compMulArray << (len + 1) result = BitArray(int=num2, length=len) result.prepend(BitArray(int=0, length=len)) result = result << (1) for i in range(len): if result[-2:] == '0b01': result = BitArray(int=result.int + add.int, length=totalLength) elif result[-2:] == '0b10': result = BitArray(int=result.int + sub.int, length=totalLength) result = BitArray(int=(result.int >> (1)), length=result.len) result = result[:-1] return result.bin, result.int
def attach_crc32(config_string: BitArray) -> BitArray: # 1 + x + x2 + x4 + x5 +x7 + x8 + x10 + x11 + x12 + x16 + x22 + x23 + x26 + x32. polynomial = BitArray(bin='1110 1101 1011 1000 1000 0011 0010 0000 1') # enter corrected length with CRC32 packet current_length = config_string.length length_with_crc32 = current_length + DB_ADDRESS_BITWIDTH + DB_CHANNEL_BITWIDTH + DB_LENGTH_BITWIDTH + 32 config_string.overwrite( BitArray(uint=length_with_crc32, length=DB_CONFIG_LENGTH_BITWIDTH), -DB_CONFIG_LENGTH_BITWIDTH) # attach DB_ADDRESS 0, Channel 0 for CRC32 receiver, length 32 of checksum config_string.prepend( BitArray(uint=0, length=DB_ADDRESS_BITWIDTH + DB_CHANNEL_BITWIDTH)) config_string.prepend(BitArray(uint=32, length=DB_LENGTH_BITWIDTH)) # actual CRC32 calculation divstring = config_string[: -DB_CONFIG_LENGTH_BITWIDTH] # without config length (doesn't leave db_config) divstring.prepend(BitArray(32)) # prepend empty CRC32 divstring.append( BitArray(1)) # attach a 0 to make indexing from LSB side easier for j in range(1, divstring.length - 32): if divstring[-(j + 1)] == 1: divstring[-(j + 33):-j] ^= polynomial remainder = divstring[0:32] config_string.prepend(remainder) return config_string
def from_data(cls, databytes): values = dict.fromkeys(MdatStateMessage.fields) # accept either the full frame payload or just the data after the CCL type identifier if (len(databytes) > 31): databytes = databytes[1:-1] d = BitStream(databytes) values['mode'] = 'MDAT_STATE' lat_bits = BitArray(d.read('bits:24')) if lat_bits[0] == 1: lat_bits.prepend('0xFF') else: lat_bits.prepend('0x00') values['latitude'] = lat_bits.floatbe * (180.0 / 2 ** 23) lon_bits = BitArray(d.read('bits:24')) if lon_bits[0] == 1: lon_bits.prepend('0xFF') else: lon_bits.prepend('0x00') values['longitude'] = lon_bits.floatbe * (180.0 / 2 ** 23) # values['latitude'] = #d.read('floatbe:24') * (180.0 / 2**23) #values['longitude'] = d.read('floatbe:24') * (180.0 / 2**23) values['fix_age'] = d.read('uint:8') * 4 values['time_date'] = decode_time_date(d.read('bits:24')) values['heading'] = d.read('uint:8') * (360.0 / 255.0) values['mission_mode_code'] = d.read('uint:3') values['mission_mode'] = mission_modes[values['mission_mode_code']] values['depth'] = decode_depth(d.read('uint:13')) values['faults_bits'] = d.read('bits:16') values['mission_leg'] = d.read('uint:8') values['estimated_velocity'] = d.read('uint:8') / 25.0 values['objective_index'] = d.read('uint:8') values['battery_percent'] = d.read('uint:8') d.read('bits:48') #values['goal_latitude'] = d.read('floatbe:24') * (180.0 / 2**23) #values['goal_longitude'] = d.read('floatbe:24') * (180.0 / 2**23) values['pitch'] = d.read('uint:6') * 180.0 / 63.0 values['oil'] = d.read('uint:5') * 100.0 / 31.0 values['gfi_percent'] = d.read('uint:5') * 100.0 / 31.0 # Make a message mdat_state = cls(values) return mdat_state
class Booths(): def calculate(self, mc, mr, x, y): self.tl = x + y + 1 print self.tl self.mA = BitArray(int=mc, length=self.tl) self.A = self.mA << (y + 1) self.mS = BitArray(int=-mc, length=self.tl) self.S = self.mS << (y + 1) self.P1 = BitArray(int=mr, length=y) self.P1.prepend(BitArray(int=0, length=x)) self.P = self.P1 << (1) for i in range(1, y + 1): if (self.P[-2:] == '0b01'): self.P = BitArray(int=self.P.int + self.A.int, length=self.tl) elif (self.P[-2:] == '0b10'): self.P = BitArray(int=self.P.int + self.S.int, length=self.tl) self.P = BitArray(int=(self.P.int >> (1)), length=self.P.len) self.P = self.P[:-1] print self.P.int return self.P.int, self.P.bin
def booth(m,q,x,y): totalLength=x+y+1 mA=BitArray(int=m,length=totalLength) print mA Add=mA<<(y+1) print Add mA1=BitArray(int=-m,length=totalLength) Sub=mA1<<(y+1) Q1=BitArray(int=q,length=y) Q1.prepend(BitArray(int=0,length=x)) P=Q1 << (1) print "Add: ",Add.bin print "Sub : ",Sub.bin for i in range(1,y+1): if P[-2:] == '0b01': P=BitArray(int=P.int+Add.int,length=totalLength) elif P[-2:] == '0b10': P=BitArray(int=P.int+Sub.int,length=totalLength) P=BitArray(int=(P.int >>1),length=P.len) P = P[:-1] #everything except the last q0 bit print "P : ",P.bin return P.bin,P.int
def booth(m, q, x, y): tlen = x + y + 1 mA = BitArray(int=m, length=tlen) A = mA << (y + 1) mA1 = BitArray(int=-m, length=tlen) S = mA1 << (y + 1) P1 = BitArray(int=q, length=x) P1.prepend(BitArray(int=0, length=y)) P = P1 << 1 for i in range(1, y + 1): if (P[-2:] == '0b01'): P = BitArray(int=P.int + A.int, length=tlen) elif (P[-2:] == '0b10'): P = BitArray(int=P.int + S.int, length=tlen) P = BitArray(int=(P.int >> 1), length=P.len) P = P[:-1] return P.int, P.bin
def gen_syndrome(pBits): errorfield = ([BitArray('0b1'), \ BitArray('0b11')]) # build all possible error combinations as # block errors for length in range(3, pBits + 1): # set first and last bit of errorstring and # count up in between for i in range(2**(length - 2)): error = BitArray('0b1') error.append(BitArray(uint=i, length=length - 2)) error.append('0b1') errorfield.append(error) for i in errorfield: error = i length = len(error) print(error) fh = open('syndrome82', 'a+') # place block errors in every possible position in # data string for pos in range(190 - length + 1): datastring = BitArray(length=190 - length - pos) datastring.append(error) datastring.append(BitArray(length=pos)) # generate syndrome from datastring syndrome = crc.crc82(datastring) # make strings a multiple of 4 bit for nicer printing datastring.prepend('0b00') syndrome.prepend('0b00') fh.write(str(syndrome) + ' ' + str(datastring) + '\n') fh.close()
def gen_syndrome(pBits): errorfield = ([BitArray('0b1'), \ BitArray('0b11')]) # build all possible error combinations as # block errors for length in range(3,pBits+1): # set first and last bit of errorstring and # count up in between for i in range(2**(length-2)): error = BitArray('0b1') error.append(BitArray(uint=i, length=length-2)) error.append('0b1') errorfield.append(error) for i in errorfield: error = i length = len(error) print(error) fh = open('syndrome82','a+') # place block errors in every possible position in # data string for pos in range(190-length+1): datastring = BitArray(length=190-length-pos) datastring.append(error) datastring.append(BitArray(length=pos)) # generate syndrome from datastring syndrome = crc.crc82(datastring) # make strings a multiple of 4 bit for nicer printing datastring.prepend('0b00') syndrome.prepend('0b00') fh.write(str(syndrome) + ' ' + str(datastring) + '\n') fh.close()
def generate_config_bitstring(self, config_list) -> BitArray: configbits = BitArray(0) if not super().find_block_config(config_list): return configbits db_vector_width = self.db_component["DB_VECTOR_WIDTH"] value = self.block_config["CONFIGURABLE"]["VALUE"] configbits.prepend(BitArray(uint=0, length=db_bitwidths["CHANNEL"])) configbits.prepend( BitArray(uint=self.db_address, length=db_bitwidths["ADDRESS"])) configbits.prepend( BitArray(uint=db_vector_width, length=db_bitwidths["LENGTH"])) configbits.prepend(BitArray(uint=value, length=db_vector_width)) return configbits
def loadImage(input, output, text, key): img = Image.open(input) # TODO - assert RGB/RGBA print img.mode #text = "Hello World!" bits = BitArray(bytes=text) lbits = BitArray(hex(bits.len)) lbits.prepend(32 - lbits.len) print text print bits.bin print lbits.bin # print bits[1] & 1 data = img.getdata() # print len(data) counter = 0 newdata = [] for i in data: c = counter - lbits.len p = counter % len(key) if (counter < lbits.len): q = (key[p] ^ (lbits[counter] & 1)) newdata.append((i[0] ^ q,i[1],i[2],255)) elif (c < bits.len): q = (key[p] ^ (bits[c] & 1)) # print "q:" + str(q) + " ,i:" + str(i[0]) + " ,i ^ q:" + str(i[0] ^ q) newdata.append((i[0] ^ q,i[1],i[2],255)) else: newdata.append((i[0],i[1],i[2],255)) counter += 1 # for i in newdata: # print i img.putdata(newdata) img.save(output)
def encode(em_tag_id): tag_bit_array = BitArray(em_tag_id) if len(tag_bit_array.hex) > EM_TAG_ID_LEN * 2: raise ValueError("Em410x tag ID must shorter than %s bytes" % EM_TAG_ID_LEN) if len(tag_bit_array.hex) < EM_TAG_ID_LEN * 2: warnings.warn("Em410x tag ID length usually equal %s bytes" % EM_TAG_ID_LEN) tag_bit_array.prepend("0x" + "0" * (EM_TAG_ID_LEN * 2 - len(tag_bit_array.hex))) bit_with_parity = "" count_of_one = 0 for i in range(0, len(tag_bit_array.bin)): bit_with_parity += tag_bit_array.bin[i] if tag_bit_array.bin[i] == "1": count_of_one += 1 if (i + 1) % 4 == 0: if count_of_one % 2 == 0: bit_with_parity += "0" else: bit_with_parity += "1" count_of_one = 0 col_parity = "" for i in range(0, 4): pos = i count_of_one = 0 while pos < len(bit_with_parity): if bit_with_parity[pos] == "1": count_of_one += 1 pos += 5 if count_of_one % 2 == 0: col_parity += "0" else: col_parity += "1" bit_with_parity = bit_with_parity + col_parity return BitArray("0b" + "111111111" + bit_with_parity + "0")
def generate_config_bitstring(self, config_list) -> BitArray: configbits = BitArray(0) if not super().find_block_config(config_list): return configbits db_register_width = 32 for i in range(0, 4): value = self.block_config["CONFIGURABLE"]["REGISTER_" + f'{i:02d}' + "_VALUE"] configbits.prepend(BitArray(uint=i, length=db_bitwidths["CHANNEL"])) configbits.prepend( BitArray(uint=self.db_address, length=db_bitwidths["ADDRESS"])) configbits.prepend( BitArray(uint=db_register_width, length=db_bitwidths["LENGTH"])) configbits.prepend(BitArray(uint=value, length=db_register_width)) return configbits
class DiveBits_configstring: configbits: BitArray config_data: dict config_file: str config_name: str components: list block_configs: list def __init__(self, config_file: str, components: list): self.configbits = BitArray(0) self.config_file = os.path.basename(config_file) self.components = components self.config_name = os.path.basename(config_file[:-5]) # open configuration file based on template if config_file[-4:].lower() == "yaml": self.config_data = yaml.safe_load(open(config_file)) if config_file[-4:].lower() == "json": self.config_data = json.load(open(config_file)) self.block_configs = self.config_data['db_components'] def generate_configstring(self): # iterate of blocks for comp in self.components: self.configbits.prepend( comp.generate_config_bitstring(self.block_configs)) # insert length into lower end of bitstring self.configbits.append( BitArray(uint=self.configbits.length, length=db_bitwidths["CONFIG_LENGTH"])) def add_crc32(self): # 1 + x + x2 + x4 + x5 +x7 + x8 + x10 + x11 + x12 + x16 + x22 + x23 + x26 + x32. polynomial = BitArray(bin='1110 1101 1011 1000 1000 0011 0010 0000 1') # enter corrected length with CRC32 packet current_length = self.configbits.length len_w_crc32 = current_length + db_bitwidths["ADDRESS"] + db_bitwidths[ "CHANNEL"] + db_bitwidths["LENGTH"] + 32 self.configbits.overwrite( BitArray(uint=len_w_crc32, length=db_bitwidths["CONFIG_LENGTH"]), -db_bitwidths["CONFIG_LENGTH"]) # attach DB_ADDRESS 0, Channel 0 for CRC32 receiver, length 32 of checksum self.configbits.prepend( BitArray(uint=0, length=db_bitwidths["ADDRESS"] + db_bitwidths["CHANNEL"])) self.configbits.prepend( BitArray(uint=32, length=db_bitwidths["LENGTH"])) # actual CRC32 calculation divstring = self.configbits[:-db_bitwidths[ "CONFIG_LENGTH"]] # without config length (doesn't leave db_config) divstring.prepend(BitArray(32)) # prepend empty CRC32 divstring.append( BitArray(1)) # attach a 0 to make indexing from LSB side easier for j in range(1, divstring.length - 32): if divstring[-(j + 1)] == 1: divstring[-(j + 33):-j] ^= polynomial remainder = divstring[0:32] self.configbits.prepend(remainder) def write_memfile(self, mem_files_path: str): # extend bitstring to multiple of 8 if (self.configbits.length % 8) != 0: missing_bits = 8 - (self.configbits.length % 8) self.configbits.prepend(BitArray(missing_bits)) # generate mem output file memfile = open(mem_files_path + self.config_name + ".mem", "w") memfile.write("// \n") memfile.write("// " + self.config_name + ".mem\n") memfile.write("// generated " + datetime.now().strftime("%b %d, %Y - %H:%M:%S") + "\n") memfile.write("// from DiveBits configuration data in " + self.config_file + "\n") memfile.write("// required to make bitstream " + self.config_name + ".bit\n") memfile.write("// \n") memfile.write("@0000\n") xpos = 0 while self.configbits.length > 0: memfile.write(self.configbits[-8:].hex.upper() + " ") del self.configbits[-8:] xpos = (xpos + 1) % 16 if xpos == 0: memfile.write("\n") memfile.write("\n") memfile.close() # configbits is empty after this! # STATIC METHODS @staticmethod def calculate_configlength(components: list, crc: bool, bram_tcl_file: str): bitcount = db_bitwidths["CONFIG_LENGTH"] for comp in components: bitcount += comp.num_configbits() if crc: bitcount += (db_bitwidths["ADDRESS"] + db_bitwidths["CHANNEL"] + db_bitwidths["LENGTH"] + 32) bram32cnt = bitcount // 32768 # integer division (floor) if (bitcount % 32768) != 0: bram32cnt += 1 # ceiling print("DiveBits component extraction:") print(" Complete number of DB config bits:", bitcount) print(" Number of RAMB36 required:", bram32cnt) # Generate Tcl command to set required number of BRAMs tcl_file = open(bram_tcl_file, 'w') tcl_file.write("global REQUIRED_BRAMS\n") tcl_file.write("set REQUIRED_BRAMS " + str(bram32cnt) + "\n") tcl_file.close()
def testPrepend(self): s = BitArray("0b0") s.prepend([1]) self.assertEqual(s, [1, 0])
def testPrepend(self): s = BitArray('0b0') s.prepend([1]) self.assertEqual(s, [1, 0])
def encode(self, frame): frame = BitArray( "0b"+ re.sub("(" + self.pattern + ")", self.bitStuffedPattern, frame.bin)) frame.append(self.flag) frame.prepend(self.flag) return frame