def ttl_read(self): sp = self.create_WASYNC_PAR() sp.s_Type = L_ASYNC_TTL_INP self.io_async(sp) ret = BitArray(uint=sp.Data[0], length=16) ret.reverse() return ret
def get_word(self, allow_recalc=False): word = BitArray(0) for i in range(5): b = self.buf.popleft() if b >> 6 != 1: pass #print("6-of-8 decode wrong") #raise RTCMBitError() b = BitArray(uint=(b&0x3f), length=6) b.reverse() word.append(b) if self.p30: word ^= BitArray(uint=0x3fffffc0, length=30) print(hex(word.uint)) if allow_recalc and self.calculate_parity(word) != word.uint & 0x3f: self.p29 = 1 if self.calculate_parity(word) != word.uint & 0x3f: raise RTCMParityError() self.p30 = word.uint & 1 self.p29 = (word.uint & 2) >> 1 return word
def get_word(self, allow_recalc=False): word = BitArray(0) for i in range(5): b = self.buf.popleft() if b >> 6 != 1: pass #print("6-of-8 decode wrong") #raise RTCMBitError() b = BitArray(uint=(b & 0x3f), length=6) b.reverse() word.append(b) if self.p30: word ^= BitArray(uint=0x3fffffc0, length=30) print(hex(word.uint)) if allow_recalc and self.calculate_parity(word) != word.uint & 0x3f: self.p29 = 1 if self.calculate_parity(word) != word.uint & 0x3f: raise RTCMParityError() self.p30 = word.uint & 1 self.p29 = (word.uint & 2) >> 1 return word
def convert_value(frame_data, item): convert_value = '' if XMLParser.Abytepos in item.keys(): bytedata = BitArray() bytepos = item.get(XMLParser.Abytepos) if ',' in bytepos or '-' in bytepos: for pos_str in bytepos.split(','): pos_str = pos_str.replace(' ', '') if '-' not in pos_str: bytedata.append(frame_data[int(pos_str):int(pos_str) + 1]) elif '-' in pos_str: min_pos_str, max_pos_str = pos_str.split('-') for pos in range(int(min_pos_str), int(max_pos_str) + 1): bytedata.append(frame_data[pos:pos + 1]) else: bytedata.append(frame_data[int(bytepos):int(bytepos) + 1]) convert_value = convert(item, bytedata) elif XMLParser.Abitpos in item.keys(): byte_pos, bit_pos = item.get(XMLParser.Abitpos).split(',') bytedata = BitArray('uint:8={}'.format(frame_data[int(byte_pos)])) bytedata.reverse() bitdata = bytedata[int(bit_pos):int(bit_pos) + 1] convert_value = convert(item, bitdata) return convert_value
def xvcShift(TMS, TDI): numBits = TMS.len print("TMS: ", TMS) print("TDI: ", TDI) ## Pad to nearest byte alignment TMS += BitArray((8 - numBits) % 8) TDI += BitArray((8 - numBits) % 8) ## Make "little-endian" essentially where bit 0 of first byte is ## the first bit out. TMS.reverse() TMS.byteswap() TDI.reverse() TDI.byteswap() msg = numBits.to_bytes(4, byteorder='little') + TMS.bytes + TDI.bytes resp = xvcdSend('shift:', msg, TMS.len // 8) TDO = BitArray(resp) TDO.byteswap() TDO.reverse() TDO = TDO[0:numBits] #print("< 0x{} == ".format(resp.hex()), TDO) print("< 0x{}".format(resp.hex())) print("TDO: ", TDO) print() return TDO
def encode(self, value): ''' :param value: value to encode ''' kassert.is_of_types(value, Bits) result = BitArray(value) result.reverse() return result
def encode(x): n = ceil(log2(x + 1) / 8) if x > 0 else 1 z = "" for i in range(n): temp = x % 256 temp = BitArray(uint=temp, length=8) temp.reverse() z += temp.bin x //= 256 return z, n
def GenerateValidDominos(Start = 0, End = 4095): logging.debug("Checking Domino Values from {} to {}" . format(Start, End)) bPass = 1 Row1 = 0 Row2 = 0 ValidValues = [] for x in range(Start,(End+1),1): bPass = True DPips = BitArray('0x000') DPips.uint = x Row1 = DPips[:6] Row2 = DPips[-6:] logging.debug("Index Value:{} Binary Value:{}" .format(x,DPips.bin)) #Row 1 and 2 Pip Count R1_PC = len(list(Row1.findall([1]))) R2_PC = len(list(Row2.findall([1]))) #Total pips between rows must be 6. if (R1_PC + R2_PC) != 6: bPass = False logging.debug("Row 1 Value:{} Binary Value:{} Pip Count:{}" .format(Row1.uint, Row1.bin, R1_PC)) logging.debug("Row 2 Value:{} Binary Value:{} Pip Count:{}" .format(Row2.uint, Row2.bin, R2_PC)) logging.debug("Pip count validity: {}" . format(bPass)) #Generate the reverse of the bit stream. DFlip = BitArray('0x000') DFlip.uint = x DFlip.reverse() ReversedValue = DFlip.uint logging.debug("Flipped Row Value:{} Binary Value:{}" .format(ReversedValue, DFlip.bin)) #The domino is a mirror iamge of itself and is invalid. if (ReversedValue == x): logging.debug("Fail: Mirror Domino") bPass = False #The rotated domino exists as a prior value. if (ReversedValue in ValidValues): logging.debug("Fail: Exists previously (rotated)") bPass = False #The specified domino passed all rules and is valid. if (bPass == True): ValidValues.append(x) logging.debug("Passed: Added Value {}({}) to list." . format(x, DPips.bin)) logging.debug("---") logging.debug(ValidValues) return ValidValues
def render_calibrator(image, block_height, block_width, pixel_width): '''This creates the checkboard-like pattern along the top and left of the first frame of video streams, and every frame of image streams. This is what the reader uses to initially lock onto the frame. Stream block_width and block_height are encoded into this pattern, using alternating color palettes so no two repeating values produce a continuous block of color, interfering with the frame lock process.''' initializer_palette_dict_a = ValuesToColor(palette_grabber('1'), 'initializer_palette A') initializer_palette_dict_b = ValuesToColor(palette_grabber('11'), 'initializer_palette B') draw = ImageDraw.Draw(image) draw.rectangle((0, 0, pixel_width - 1, pixel_width - 1), fill='rgb(0,0,0)') block_width_encoded = BitArray(uint=block_width, length=block_width - 1) block_width_encoded.reverse() readable_block_width = ConstBitStream(block_width_encoded) for i in range(block_width - 1): next_bit = readable_block_width.read('bits : 1') if i % 2 == 0: color_value = initializer_palette_dict_b.get_color( ConstBitStream(next_bit)) else: color_value = initializer_palette_dict_a.get_color( ConstBitStream(next_bit)) draw.rectangle((pixel_width * i + pixel_width, 0, pixel_width * (i + 1) - 1 + pixel_width, pixel_width - 1), fill=f'rgb{str(color_value)}') block_height_encoded = BitArray(uint=block_height, length=block_height - 1) block_height_encoded.reverse() readable_block_height = ConstBitStream(block_height_encoded) for i in range(block_height - 1): next_bit = readable_block_height.read('bits : 1') if i % 2 == 0: color_value = initializer_palette_dict_b.get_color( ConstBitStream(next_bit)) else: color_value = initializer_palette_dict_a.get_color( ConstBitStream(next_bit)) draw.rectangle( (0, pixel_width * i + pixel_width, pixel_width - 1, pixel_width * (i + 1) - 1 + pixel_width), fill=f'rgb{str(color_value)}') return image
def verifyBlocksX(image, pixelWidth, blockWidthEstimate, combinedColors, initializerPaletteADict, initializerPaletteBDict, override=False): '''This is a function used within frameLockOn(). It verifies the correct values for the X axis.''' calibratorBitsX = BitArray() for xBlock in range(17): snappedValue = colorSnap(scanBlock(image, pixelWidth, xBlock, 0), combinedColors) if xBlock % 2 == 0: calibratorBitsX.append( initializerPaletteADict.getValue(snappedValue)) else: calibratorBitsX.append( initializerPaletteBDict.getValue(snappedValue)) calibratorBitsX.reverse() readCalibratorX = ConstBitStream(calibratorBitsX) if readCalibratorX.read('uint:16') != blockWidthEstimate: if override == True: logging.warning( 'blockWidthOverride is not equal to what was read on calibrator. Aborting...' ) else: logging.warning( 'blockWidth verification does not match initial read. This could be the result of \n' 'sufficiently distorted frames. Aborting...') return False if readCalibratorX.read('bool') != False: logging.warning('0,0 block unexpected value. Aborting...') return False if override == True: logging.info('blockWidthOverride successfully verified.') else: logging.debug('blockWidth successfully verified.') return True
def write_tms_tdi_read_tdo(self, tms, tdi): """Write out TMS bits while holding TDI constant and reading back in TDO""" if not (isinstance(tms, BitStream) or isinstance(tms, BitArray)): raise JtagError('Expect a BitStream or BitArray') length = len(tms) if not (0 < length < 8): raise JtagError('Invalid TMS length') tms.reverse() # must reverse bits since only lsb write seems to be supported tms.prepend(8-len(tms)) # prepend 0's to be 8 bits long # left-most bit will be for TDI if isinstance(tdi, BitStream) or isinstance(tdi, BitArray): tms[0] = tdi[0] elif isinstance(tdi, bool): tms[0] = tdi else: raise JtagError('Incorrect type for tdi - must be BitStream, BitArray or bool') # apply the last TDI bit #@@@if self._last is not None: #@@@ out[7] = self._last # print("TMS", tms, (self._last is not None) and 'w/ Last' or '') # reset last bit #@@@self._last = None ## Send the byte to the FTDI cmd = array('B', (Ftdi.RW_BITS_TMS_PVE_NVE, length-1, tms.uint)) self._stack_cmd(cmd) self.sync() ## Read the response from FTDI data = self._ftdi.read_data_bytes(1, 4) if (len(data) != 1): raise JtagError('Not all data read! Expected {} bytes but only read {} bytes'.format(1,len(data))) tdo = BitArray(data) # FTDI handles returned LSB bit data by putting the first bit # in bit 7 and shifting to the right with every new bit. So # the first bit clocked will be in the lowest bit number, but # which bit number it will be in depends on how many bits # clocked. [It is kinda stupid, if you ask me. I think the bit # order should be the same as tehe bit written, but they # aren't.] tdo = tdo[:length] # return to bitstring bit ordering with left-most bit the lsb tdo.reverse() return tdo
def checkBH(bh, lf): if bh[0] == 3 and bh[1] == 16384 and bh[3] == 22 and bh[10] == 48059: lf.write('New buffer started.\n') bitflags = BitArray(int=bh[7], length=16) bitflags.reverse() data_format = '>HHH' if bitflags[4] or bitflags[5]: data_format += 'H' if bitflags[5]: data_format += 'HH' if bitflags[6]: data_format += 'HH' return (data_format) else: lf.write('Buffer header error at: ') lf.write(str(data_file.tell()) + '\n') return ('0')
def rrs(ba): if isinstance(ba, str): ba = BitArray(bytes(ba, "utf-8")) out = [] for _ in range(ba.length): try: out.append(ba.bytes.decode('utf-8')) except UnicodeDecodeError: pass ba.ror(1) ba.reverse() for _ in range(ba.length): try: out.append(ba.bytes.decode('utf-8')) except UnicodeDecodeError: pass ba.ror(1) ba.reverse() return out
def encode(data: bytes): root = build_tree(data) translation_list = build_character_translation(root, []) # print(f'translation list {translation_list}') translation = merge_dictionaries(translation_list) # print(f'translation {translation}') translated = list(itertools.chain(*[translation.get(byte) for byte in data])) # print(f'l translated {len(translated)}') additional_bytes = len(translated) % 8 # print(f'additional bytes {additional_bytes}') x = BitArray(translated) + BitArray([0] * (8 - additional_bytes)) x.reverse() x.byteswap() # print (f'x {x.bin}') encoded_bytes = x.tobytes() # print(f'encoded bytes: {encoded_bytes}') root.additional_bytes = additional_bytes serialised_tree = DefaultEncoder().encode(root) output = bytes(serialised_tree, 'ascii') + encoded_bytes return output
def verify_blocks_x(image, pixel_width, block_width_estimate, combined_colors, initializer_palette_a_dict, initializer_palette_b_dict, override = False): '''This is a function used within frame_lock_on(). It verifies the correct values for the X axis.''' calibrator_bits_x = BitArray() for x_block in range(17): snapped_value = color_snap(scan_block(image, pixel_width, x_block, 0), combined_colors) if x_block % 2 == 0: calibrator_bits_x.append(initializer_palette_a_dict.get_value(snapped_value)) else: calibrator_bits_x.append(initializer_palette_b_dict.get_value(snapped_value)) calibrator_bits_x.reverse() read_calibrator_x = ConstBitStream(calibrator_bits_x) if read_calibrator_x.read('uint:16') != block_width_estimate: if override == True: logging.warning('block_width_override is not equal to what was read on calibrator. Aborting...') else: logging.warning('block_width verification does not match initial read. This could be the result of \n' 'sufficiently distorted frames. Aborting...') return False if read_calibrator_x.read('bool') != False: logging.warning('0,0 block unexpected value. Aborting...') return False if override == True: logging.info('block_width_override successfully verified.') else: logging.debug('block_width successfully verified.') return True
def main(): file = open(sys.argv[1], "rb") msg = ConstBitStream(file) s_in = BitArray() keys = {Bits(''): 0} s_out = BitArray() count = 1 n_bits = 0 while True: try: s_in.append(msg.read(1)) except ReadError: break #Se a palavra nao tiver no dicionario if Bits(s_in) not in keys: # x = yb y = s_in[:-1] b = s_in[-1:] pos = keys[Bits(y)] #log base 2 |keys| n_bits = ceil(log2(len(keys))) if n_bits != 0: prefix = Bits(uint=int(pos), length=n_bits) else: prefix = Bits('') s_out.append(Bits('0b' + str(prefix.bin) + str(b.bin))) keys[Bits(s_in)] = count count += 1 s_in.clear() #Add padding: 00000 10101 #Numero de zeros é o tamanho dos bits extra para depois no descompressor saber if s_in[:1].bin == Bits(1): z = Bits('0b' + '0' * len(s_in)) else: z = Bits('0b' + '1' * len(s_in)) s_in.reverse() s_out.reverse() s_out.append(s_in) s_out.append(z) s_out.reverse() with open(sys.argv[2], 'wb') as f_out: s_out.tofile(f_out) file.close()
def _get_group_number(self, nbunch): func = permutations if self._gnx.is_directed() else combinations # Reversing is a technical issue. We saved our node variations files bit_form = BitArray(self._gnx.has_edge(n1, n2) for n1, n2 in func(nbunch, 2)) bit_form.reverse() return bit_form.uint
def pixelCreep(pixelObject, initializerPaletteA, initializerPaletteB, combinedColors, initializerPaletteADict, initializerPaletteBDict, imageWidth, imageHeight, width): '''This function moves across the calibrator on the top and left of the frame one pixel at a time, and after 'snapping' the colors, decodes an unsigned integer from each axis, which if read correctly, is the block width and block height of the frame. ''' calibratorBits = BitArray() snappedValues = [] activeColor = (0, 0, 0) activeDistance = 0 pixelOnDimension = 1 paletteAIsActive = False if width == True: axisOnImage = pixelOnDimension, 0 axisAnalyzed = imageWidth else: axisOnImage = 0, pixelOnDimension axisAnalyzed = imageHeight for value in range(16): while True: if width == True: axisOnImage = pixelOnDimension, 0 axisAnalyzed = imageWidth else: axisOnImage = 0, pixelOnDimension axisAnalyzed = imageHeight newPaletteLocked = False activeScan = pixelObject[axisOnImage] activeDistance = returnDistance(activeScan, activeColor) pixelOnDimension += 1 if activeDistance < 100: # Iterating over same colored blocks, until distance exceeds 100. continue else: # We are determining if we are within < 100 dist of a new color, or are in fuzzy space. if paletteAIsActive == False: activePalette = initializerPaletteB.colorSet else: activePalette = initializerPaletteA.colorSet for color in activePalette: activeDistance = returnDistance(activeScan, color) if activeDistance < 100: paletteAIsActive = not paletteAIsActive newPaletteLocked = True break else: continue if newPaletteLocked == True: break activeColor = colorSnap(activeScan, combinedColors) snappedValues.append(activeColor) if value % 2 != 0: calibratorBits.append( initializerPaletteADict.getValue(activeColor)) else: calibratorBits.append( initializerPaletteBDict.getValue(activeColor)) activeDistance = 0 calibratorBits.reverse() readCalibratorBits = ConstBitStream(calibratorBits) blockDimensionGuess = readCalibratorBits.read('uint:16') pixelWidth = axisAnalyzed / blockDimensionGuess return pixelWidth, blockDimensionGuess
def right_encode(x): z, n = encode(x) temp = BitArray(uint=n, length=8) temp.reverse() z += temp.bin return z
# -*- coding: utf-8 -*- # # Python 2.7.1 # from bitstring import BitArray fname = 'image.jpg' with open(fname, 'r+b') as fh: byte_map = [ord(b) for b in fh.read(4)] byte_list = [byte_map[0], byte_map[1], byte_map[2], byte_map[3]] print 'retrieved', len(byte_list), 'from file', fname offset = 0 for ascii_val in byte_list: bin_val = BitArray(hex(ascii_val)) print bin_val.bin BitArray.reverse(bin_val) print bin_val.bin fh.seek(offset) bin_val.tofile(fh) print 'writing offset', offset, 'of file', fname offset += 1 fh.close()
#print("drive space %f %s" % (drive_space, default_unit)) array_width = args.words * args.drive_pitch #print("array width %f %s" % (array_width, default_unit)) sense_space = (args.sense_pitch - (3 * args.trace_width)) / 3.0 #print("sense space %f %s" % (sense_space, default_unit)) array_height = args.bits * args.sense_pitch - sense_space #print("array height %f %s" % (array_height, default_unit)) data = BitArray(args.input) if len(data) != args.words * args.bits: raise RuntimeError("input file size %d bits, should be %d bits\n" % (len(data), args.words * args.bits)) for i in range(0, len(data), 8): data.reverse(i, i+8) board = EagleBoardFile(numlayers = 4) board.add_rectangular_board_outline(0, 0, args.width, args.length); y = args.length / 2.0 - ((args.words // 2) - 0.5) * args.drive_pitch word_y = [None] * args.words for word in range(args.words): word_y [word] = [y, y - (args.trace_width + drive_space) / 2.0, y + (args.trace_width + drive_space) / 2.0] y += args.drive_pitch
def __createpocsagmsg(self, address, source, txt): # checking input if not (0 < address <= 0x1fffff): raise ValueError(address) #end if if not (0 <= source <= 3): raise ValueError(source) #nd if if len(txt) == 0: raise ValueError(txt) #end if # if len(txt) >= 40: # txt=txt[:39] # print("Warning, text truncated to 39 characters: {txt}".format(txt=txt)) #end if # init pocsag message # init data # 2 batches # 1 batch = sync codeword + 8 frames # 1 frame = 1 codeword syncpattern = 0xAAAAAAAA synccodeword = 0x7cd215d8 idlepattern = 0x7ac9c197 # init all codewords with idle pattern: 2 batches = 16 frames = 32 codewords codeword = [idlepattern for i in range(32)] # part 1: address + source # parse address and source addressline = address >> 3 # add address-source addressline <<= 2 addressline += source # the message starts at the frame address determined by the last 3 bits of the address cwnum = ((address % 8) << 1) # codeword number codeword[cwnum] = self.__CalculateCRCandParity(datatype=0, data=addressline) # part 2: text # 2.1 convert text into int, also add EOT char ts = [ord(c) for c in txt] + [0x04] # 2.2 make sure all characers are 7 bit ts = list(map(lambda x: x % 128, ts)) # 2.3 create one big list of bits textbits = '' for c in ts: # BitArray(uint=c,length=7).bin to convert character to 7-character bit-string) # note, for transmission, the bit-order must be reversed charbits = BitArray(uint=c, length=7) # reverse order of bits charbits.reverse() # add to total string textbits += charbits.bin #end for nbits = len(textbits) # 2.4 make the list of bits a multiple of 20 bits bitstoadd = 20 - (nbits % 20) if bitstoadd == 20: bitstoadd = 0 #end if bitstoadd_rest = bitstoadd % 2 bitstoadd_2bit = bitstoadd >> 1 textbits += '01' * bitstoadd_2bit if bitstoadd_rest == 1: textbits += '0' #end if # 2.5 for every block of 20 bits, calculate crc and partity, and add to codeword ncw = len(textbits) / 20 # number of codewords startbit = 0 stopbit = 20 # (actually, the 19th bit) for i in range(ncw): thiscw = textbits[startbit:stopbit] thiscw_i = int(thiscw, 2) # convert list of bits to int #move up all pointers startbit = stopbit # stopbit is startbit + 20 stopbit += 20 #codeword pointer cwnum += 1 # calculate CRC for a text block (datatype = 1) codeword[cwnum] = self.__CalculateCRCandParity(datatype=1, data=thiscw_i) #end for (number of # done # now create complete pocsag message # sync pattern ret = [syncpattern for i in range(18)] # add sync codeword of 1st batch ret.append(synccodeword) # add frames 0 to 7 (i.e. codewords 0 to 15) ret += [codeword[n] for n in range(16)] # create add 2nd batch if the text has spilled into the 2nd batch if cwnum >= 16: # long message, 2 batches nbatch = 2 # add sync codeword ret.append(synccodeword) # and add frames 8 to 15 (i.e. codewords 16 to 31) ret += [codeword[n] for n in range(16, 32)] else: # short message, 1 batch nbatch = 1 #end else - ifif return ((nbatch, ret))
def left_encode(x): z, n = encode(x) temp = BitArray(uint=n, length=8) temp.reverse() z = temp.bin + z return z
def pixel_creep(image, initializer_palette_a, initializer_palette_b, combined_colors, initializer_palette_a_dict, initializer_palette_b_dict, image_width, image_height, width): '''This function moves across the calibrator on the top and left of the frame one pixel at a time, and after 'snapping' the colors, decodes an unsigned integer from each axis, which if read correctly, is the block width and block height of the frame. ''' calibrator_bits = BitArray() snapped_values = [] active_color = (0, 0, 0) active_distance = 0 pixel_on_dimension = 1 palette_a_is_active = False if width == True: axis_on_image = pixel_on_dimension, 0 axis_analyzed = image_width else: axis_on_image = 0, pixel_on_dimension axis_analyzed = image_height for value in range(16): while True: if width == True: axis_on_image = 0, pixel_on_dimension axis_analyzed = image_width else: axis_on_image = pixel_on_dimension, 0 axis_analyzed = image_height new_palette_locked = False active_scan = flip(image[axis_on_image]) active_distance = return_distance(active_scan, active_color) pixel_on_dimension += 1 if active_distance < 100: # Iterating over same colored blocks, until distance exceeds 100. continue else: # We are determining if we are within < 100 dist of a new color, or are in fuzzy space. if palette_a_is_active == False: active_palette = initializer_palette_b.color_set else: active_palette = initializer_palette_a.color_set for color in active_palette: active_distance = return_distance(active_scan, color) if active_distance < 100: palette_a_is_active = not palette_a_is_active new_palette_locked = True break else: continue if new_palette_locked == True: break active_color = color_snap(active_scan, combined_colors) snapped_values.append(active_color) if value % 2 != 0: calibrator_bits.append(initializer_palette_a_dict.get_value(active_color)) else: calibrator_bits.append(initializer_palette_b_dict.get_value(active_color)) active_distance = 0 calibrator_bits.reverse() read_calibrator_bits = ConstBitStream(calibrator_bits) block_dimension_guess = read_calibrator_bits.read('uint:16') pixel_width = axis_analyzed / block_dimension_guess return pixel_width, block_dimension_guess