Esempio n. 1
0
 def __getValueFromTwoRegisters(self, registers):
     lowWord = BitArray(uint=registers[0], length=16)
     highWord = BitArray(uint=registers[1], length=16)
     total = BitArray(lowWord)
     total.insert(highWord, 0)
     return total.int
         
Esempio n. 2
0
 def send(self, msg, type_=34):
     data = BitArray(f"int:8={type_}")
     data.append(protocol.encodeArray(msg))
     data.insert(self._make_header(data), 0)
     try:
         self.connection.send(data.bytes)
     except (BrokenPipeError, OSError):
         self.connection.close()
    def _ensure_padding(self, cipher_stream):
        stream = BitArray(hex=cipher_stream)
        stream_len = stream.len
        while stream_len % 8:
            stream.insert('0b0', 0)
            stream_len = stream_len + 1

        return stream
    def _ensure_padding(self, cipher_stream):
        stream = BitArray(hex=cipher_stream)
        stream_len = stream.len
        while stream_len % 8:
            stream.insert('0b0', 0)
            stream_len = stream_len + 1

        return stream
Esempio n. 5
0
	def string_to_bitarray(self, _string, _maxsize=448):
		b = BitArray()
		pos = 0
		if (_string):
			for c in _string:
				c_str = "{:#09b}".format(ord(c))
				print("{:s}:{:s}".format(c, c_str))
				b.insert(c_str, pos)
				pos += 7
		if (len(b.bin) < _maxsize):
			b.insert("{:#09b}".format(TERMINATOR), pos)
		if (len(b.bin) > _maxsize):
			raise Exception("Size of bit array exceeds the maximum size allowed ({:d}).".format(_maxsize))
		return b
Esempio n. 6
0
 def string_to_bitarray(self, _string, _maxsize=448):
     b = BitArray()
     pos = 0
     if (_string):
         for c in _string:
             c_str = "{:#09b}".format(ord(c))
             print("{:s}:{:s}".format(c, c_str))
             b.insert(c_str, pos)
             pos += 7
     if (len(b.bin) < _maxsize):
         b.insert("{:#09b}".format(TERMINATOR), pos)
     if (len(b.bin) > _maxsize):
         raise Exception(
             "Size of bit array exceeds the maximum size allowed ({:d}).".
             format(_maxsize))
     return b
Esempio n. 7
0
 def __setSubnet(self):
     oldSubnet = self.__safeReadHoldingRegisters(32776, 2)
     firstOctet = Bits(uint=255, length=8)
     secondOctet = Bits(uint=255, length=8)
     thirdOctet = Bits(uint=255, length=8)
     fourthOctet = Bits(uint=0, length=8)
 
     firstWord = BitArray(secondOctet)
     firstWord.insert(firstOctet, 0)
 
     secondWord = BitArray(fourthOctet)
     secondWord.insert(thirdOctet, 0)
     #print(secondWord.bin)
     commands = []
     commands.append(secondWord.uint)
     commands.append(firstWord.uint)
     self.__safeWriteRegisters(32776, commands)
Esempio n. 8
0
 def __setAddress(self):
     oldAddress = self.__safeReadHoldingRegisters(32774,2)
     firstOctet = Bits(uint=192, length=8)
     secondOctet = Bits(uint=168, length=8)
     thirdOctet = Bits(uint=0, length=8)
     fourthOctet = Bits(uint=12, length=8)
 
     firstWord = BitArray(secondOctet)
     firstWord.insert(firstOctet, 0)
 
     secondWord = BitArray(fourthOctet)
     secondWord.insert(thirdOctet, 0)
     
     commands = []
     commands.append(secondWord.uint)
     commands.append(firstWord.uint)
     self.__safeWriteRegisters(32774, commands)
     newAddress = self.__safeReadHoldingRegisters(32774, 2)
Esempio n. 9
0
    def generate(self, string):
        bS = BitStream()
        mode = BitArray(bin='0010')
        nBits = 9
        lenOfString = len(string)
        bLen = bin(lenOfString)
        bs = BitArray(bin=bLen)

        while bs._datastore.bitlength < 9:
            bs.insert('0b0', 0)
        bs.insert(mode, 0)

        stringPair = [string[i:i + 2] for i in range(0, len(string), 2)]

        for sp in stringPair:
            print(sp[0], sp[1])

        # number of characters read into 9 bit stream appended to mode. Now to encode the message

        pass
Esempio n. 10
0
def int_to_vlv(number: int) -> bytes:
    """Calculate variable-length time from integer"""

    assert type(number) is int, "Input should be integer"
    assert number <= 4294967295, "Woah! Number too huge. Should be <= 4294967295 "

    # inputs below 127 don't change
    try:
        if number <= 127: return number.to_bytes(1, 'big')
    except OverflowError:
        print(number)

    # get input into bit array
    number = struct.pack(
        '>I', number)  # must do big endian as midi values are read forward
    bits = BitArray(number)

    # remove 0s from beginning
    while bits[0] == 0:
        del (bits[0])

    length = len(bits)

    # insert 0 at the beginning of the final byte, signifying it is the final byte
    bits.insert(1, length - 7)
    # insert 1s at beginning of each byte, shifting the rest left
    for pos in range(length)[length - 14::-7]:
        bits.insert(1, pos)
        bits.invert(pos)

    # pad 0s to complete the first byte
    while len(bits) % 8 != 0:
        bits.insert(1, 0)

    # make first bit 1 if not already
    if bits[0] is not True:
        bits.invert(0)

    return bits.bytes
 def testInsert(self):
     s = BitArray("0b00")
     s.insert("0xf", 1)
     self.assertEqual(s, "0b011110")
Esempio n. 12
0
 def testInsert(self):
     s = BitArray('0b00')
     s.insert('0xf', 1)
     self.assertEqual(s, '0b011110')
Esempio n. 13
0
 def testInsert(self):
     s = BitArray('0b00')
     s.insert('0xf', 1)
     self.assertEqual(s, '0b011110')
Esempio n. 14
0
    def pass_1_inst(self, line, line_idx):
        # TODO: create another class that deals with ABI definitions of xC architecture
        tokens = list(filter(None, re.split('\s|\t', line)))
        if self.__asm_debug:
            print('\tinst\t: {}'.format(tokens))
        # skip assembler directives
        if tokens[0] not in self.mne_table and tokens[0] not in self.sym_table:
            if self.__asm_debug:
                print("\t// skipping assembler directive '{}'".format(tokens[0]))
            return 0
        # tokens[0] is either instruction, label, or symbol
        if tokens[0] in abi.optable:
            # instruction
            _bytecode = BitArray( '{}'.format( hex(abi.optable[tokens[0]]) ) )
            while len(_bytecode) < 6:
                _bytecode.insert('0b0',0)

            if tokens[0] in ['nop']:
                while len(_bytecode) < 64:
                    _bytecode.insert('0b0',0)

            # one-arg variable jump instructions (58-bit addr)
            if tokens[0] in ['jmp', 'jal']:
                # if this is a register
                if tokens[1].startswith('$'):
                    _regval = BitArray( '{}'.format( hex(abi.regtable[tokens[1]]) ) )
                    while len(_regval) < 6:
                        _regval.insert('0b0',0)
                    _bytecode.append(_regval)
                # else, if this is an immediate value
                elif re.match('^([0-9]+|0x([0-9a-f])+)$',tokens[1]):
                    _immval = BitArray( '{}'.format( hex(int(tokens[1],0) * 16) ) )
                    while len(_immval) < 58:
                        _immval.insert('0b0',0)
                    _bytecode.append(_immval)
                # else, this must be a symbol
                else:
                    _syment = self.sym_table[tokens[1]]
                    # { 'name' : ['LC offset', 'type (N/O/F)', 'relative? (R/A)', 'internal? (I/E)']}
                    _valid_imm_internal = (_syment[1] == 'O' and _syment[2] == 'A' and _syment[3] == 'I') \
                        or (_syment[1] == 'F' and _syment[2] == 'R' and _syment[3] == 'I')
                    # if this is a value we can immediately substitute into the instruction
                    if _valid_imm_internal:
                        _subval = BitArray( '{}'.format( hex(_syment[0] * 16) ) )
                        while len(_subval) < 58:
                            _subval.insert('0b0',0)
                        _bytecode.append(_subval)
                    elif (_syment[1] == 'O' and _syment[2] == 'R' and _syment[3] == 'I'):
                        # this is most likely a calculatable value, let's just do it now for immediate bytecode "linking purposes"
                        _sym_ariexp = _syment[0]
                        for idx in range(0, len(_sym_ariexp)):
                            if _sym_ariexp[idx] in self.sym_table:
                                _sym_ariexp[idx] = self.sym_table[_sym_ariexp[idx]][0]
                            elif _sym_ariexp[idx].isdigit():
                                _sym_ariexp[idx] = int(_sym_ariexp[idx])
                        _sym_endval = self.parse_ari(_sym_ariexp)
                        _subval = BitArray( '{}'.format( hex(_sym_endval * 8) ) )
                        while len(_subval) < 58:
                            _subval.insert('0b0',0)
                        _bytecode.append(_subval)

            # one-arg register jump instruction
            elif tokens[0] == 'jr':
                _regval = BitArray( '{}'.format( hex(abi.regtable[tokens[1]]) ) )
                while len(_regval) < 58:
                    if len(_regval) < 6:
                        _regval.insert('0b0',0)
                    else:
                        _regval.append('0b0')
                _bytecode.append(_regval)

            # two-arg non-memory instructions (50-bit immediate)
            elif tokens[0] in ['mov', 'add', 'sub']:
                _regval = None
                _immval = None
                # if first arg is a register
                if tokens[1].startswith('$'):
                    _immval = BitArray( '{}'.format( hex(abi.regtable[tokens[1]]) ) )
                    while len(_immval) < 52:
                        if len(_immval) < 6:
                            _immval.insert('0b0',0)
                        else:
                            _immval.append('0b0')
                # else, if this is an immediate value
                elif re.match('(^[0-9]+$|^0x([0-9a-f])+$)',tokens[1]):
                    # make sure it is in the valid range for these instructions
                    _tok_imm = tokens[0] + 'i'
                    _bytecode = None
                    _bytecode = BitArray( '{}'.format( hex(abi.optable[_tok_imm]) ) )
                    while len(_bytecode) < 6:
                        _bytecode.insert('0b0',0)
                    while len(_bytecode) > 6:
                        _bytecode = _bytecode[1:]
                    _immval = BitArray( '{}'.format( hex(int(tokens[1])) ) )
                    while len(_immval) < 52:
                        if int(tokens[1]) < 0:
                            _immval.insert('0b1',0)
                        else:
                            _immval.insert('0b0',0)
                # else, this must be a named literal
                else:
                    _tok_imm = tokens[0] + 'i'
                    _bytecode = None
                    _bytecode = BitArray( '{}'.format( hex(abi.optable[_tok_imm]) ) )
                    while len(_bytecode) < 6:
                        _bytecode.insert('0b0',0)
                    while len(_bytecode) > 6:
                        _bytecode = _bytecode[1:]
                    # symbol val processing
                    _syment = self.sym_table[tokens[1]]
                    # { 'name' : ['LC offset', 'type (N/O/F)', 'relative? (R/A)', 'internal? (I/E)']}
                    _valid_imm_internal = (_syment[1] == 'O' and _syment[2] == 'A' and _syment[3] == 'I') \
                        or (_syment[1] == 'F' and _syment[2] == 'R' and _syment[3] == 'I')
                    # if this is a value we can immediately substitute into the instruction
                    if _valid_imm_internal:
                        _immval = BitArray( '{}'.format( hex(_syment[0]) ) )
                        while len(_immval) < 52:
                            _immval.insert('0b0',0)
                    elif (_syment[1] == 'O' and _syment[2] == 'R' and _syment[3] == 'I'):
                        # this is most likely a calculatable value, let's just do it now for immediate bytecode "linking purposes"
                        _sym_ariexp = _syment[0]
                        for idx in range(0, len(_sym_ariexp)):
                            if _sym_ariexp[idx] in self.sym_table:
                                _sym_ariexp[idx] = self.sym_table[_sym_ariexp[idx]][0]
                            elif _sym_ariexp[idx].isdigit():
                                _sym_ariexp[idx] = int(_sym_ariexp[idx])
                        _sym_endval = self.parse_ari(_sym_ariexp)
                        _immval = BitArray( '{}'.format( hex(_sym_endval) ) )
                        while len(_immval) < 52:
                            _immval.insert('0b0',0)
                # second arg must be a register
                if tokens[2].startswith('$'):
                    _regval = BitArray( '{}'.format( hex(abi.regtable[tokens[2]]) ) )
                    while len(_regval) < 6:
                        _regval.insert('0b0',0)
                    while len(_regval) > 6:
                        _regval = _regval[1:]
                _bytecode.append(_regval)
                _bytecode.append(_immval)

            # three-arg memory instructions (46-bit addr) [format: 'LOAD reg off(mem)']
            elif tokens[0] in ['load', 'stor']:
                _rsrcvl = BitArray( '{}'.format( hex(abi.regtable[tokens[1]]) ) )
                _roffvl = None
                _rmemvl = None
                while len(_rsrcvl) < 6:
                    _rsrcvl.insert('0b0',0)
                # valid offset(memptr) format
                if re.match('^([0-9]+|0x[0-9a-f]+|[$][0-9a-z]+)[(][$][0-9a-z]+[)]$', tokens[2]):
                    tokspl = tokens[2].split('(')
                    tokspl[1] = tokspl[1][:-1]
                    # tokspl = ['offset', 'memptr']
                    # if offset starts with '$', is a register
                    if tokspl[0].startswith('$'):
                        _roffvl = BitArray( '{}'.format( hex(abi.regtable[tokspl[0]]) ) )
                        while len(_roffvl) < 46:
                            if len(_roffvl) < 6:
                                _roffvl.insert('0b0',0)
                            else:
                                _roffvl.append('0b0')
                    else:
                        _bytecode = None
                        _iminst = tokens[0] + 'i'
                        _bytecode = BitArray( '{}'.format( hex(abi.optable[_iminst]) ) )
                        while len(_bytecode) < 6:
                            _bytecode.insert('0b0',0)
                        while len(_bytecode) > 6:
                            _bytecode = _bytecode[1:]
                        _roffvl = BitArray( '{}'.format( hex(int(tokspl[0])) ) )
                        while len(_roffvl) < 46:
                            if int(tokspl[0]) < 0:
                                _roffvl.insert('0b1',0)
                            else:
                                _roffvl.insert('0b0',0)
                    # then check memptr -- must be a register
                    _rmemvl = BitArray( '{}'.format( hex(abi.regtable[tokspl[1]]) ) )
                    while len(_rmemvl) < 6:
                        _rmemvl.insert('0b0',0)

                _bytecode.append(_rsrcvl)
                _bytecode.append(_rmemvl)
                _bytecode.append(_roffvl)

            # three-arg conditional jump instructions (46-bit addr)
            elif tokens[0] in ['beq', 'bne', 'blt', 'bgt']:
                _rsrcvl = BitArray( '{}'.format( hex(abi.regtable[tokens[1]]) ) )
                while len(_rsrcvl) < 6:
                    _rsrcvl.insert('0b0',0)
                while len(_rsrcvl) > 6:
                    _rsrcvl = _rsrcvl[1:]
                _rcmpvl = BitArray( '{}'.format( hex(abi.regtable[tokens[2]]) ) )
                while len(_rcmpvl) < 6:
                    _rcmpvl.insert('0b0',0)
                while len(_rcmpvl) > 6:
                    _rcmpvl = _rcmpvl[1:]
                _bytecode.append(_rsrcvl)
                _bytecode.append(_rcmpvl)

                # symbol val processing
                _syment = self.sym_table[tokens[3]]
                # { 'name' : ['LC offset', 'type (N/O/F)', 'relative? (R/A)', 'internal? (I/E)']}
                _valid_imm_internal = (_syment[1] == 'O' and _syment[2] == 'A' and _syment[3] == 'I') \
                    or (_syment[1] == 'F' and _syment[2] == 'R' and _syment[3] == 'I')
                # if this is a value we can immediately substitute into the instruction
                if _valid_imm_internal:
                    _subval = BitArray( '{}'.format( hex(_syment[0] * 16) ) )
                    while len(_subval) < 46:
                        _subval.insert('0b0',0)
                    _bytecode.append(_subval)
                elif (_syment[1] == 'O' and _syment[2] == 'R' and _syment[3] == 'I'):
                    # this is most likely a calculatable value, let's just do it now for immediate bytecode "linking purposes"
                    _sym_ariexp = _syment[0]
                    for idx in range(0, len(_sym_ariexp)):
                        if _sym_ariexp[idx] in self.sym_table:
                            _sym_ariexp[idx] = self.sym_table[_sym_ariexp[idx]][0]
                        elif _sym_ariexp[idx].isdigit():
                            _sym_ariexp[idx] = int(_sym_ariexp[idx])
                    _sym_endval = self.parse_ari(_sym_ariexp)
                    _subval = BitArray( '{}'.format( hex(_sym_endval * 16) ) )
                    while len(_subval) < 46:
                        _subval.insert('0b0',0)
                    _bytecode.append(_subval)

            if self.__asm_debug:
                print( ">>\tbytecode: {} | len: {}".format(_bytecode.bin, len(_bytecode)) )
            self.obj_raw.append(_bytecode)
        else:
            # label or symbol, reference symtable
            if self.__asm_debug:
                print("\tsymbol: address {}".format(self.sym_table[tokens[0]]))
        return 0
 def testInsertParameters(self):
     s = BitArray('0b111')
     with self.assertRaises(TypeError):
         s.insert('0x4')
Esempio n. 16
0
 def testInsert(self):
     a = BitArray('0x0123456')
     a.insert('0xf', 4)
     self.assertEqual(a, '0x012345f6')