def audio_extract(self): ''' seperate the audio from the vedio. ''' current = self._bytes_begin while current < self._size: tag_type = self._flv_data[current] tag_data_size = bytes_to_int(self._flv_data[current + 1:current + 4]) tag_data = self._flv_data[current + 11:current + 11 + tag_data_size] if tag_type == AUDIO: if self._audio_tag_header is None: self._audio_tag_header = audio_tag_header( format(tag_data[0], 'b')) assert (self._audio_tag_header.soundformat == 10) assert (tag_data[1] == 0x00) self.calculate_audio_specific_config(tag_data[2:]) else: self._acc_data += self.make_adts_headers(tag_data_size - 2) + tag_data[2:] current += 11 + tag_data_size assert (bytes_to_int(self._flv_data[current:current + 4]) == 11 + tag_data_size) current += 4
def send_message_to_user(self, user, message, from_diffi=False): if not from_diffi and not self._K.get(user): self.diffi_with_user(user) while not self._K.get(user): time.sleep(1) if not from_diffi: key = int_to_bytes(self._K.get(user))[-32:] cipher = Salsa20.new(key=key) message = b64encode(cipher.nonce + cipher.encrypt(message.encode('utf-8'))).decode('utf-8') m = hashlib.sha256() m.update(int_to_bytes(self._password)) m.update(int_to_bytes(self._R3)) password = m.digest() password = bytes_to_int(password) data = requests.post(SERVER_ADDR, data=json.dumps( {"type": "send", "login": self._login, "password": password, "user": user, "message": message})).json() if data["error"] != "OK": r = requests.post(SERVER_ADDR, data=json.dumps({"type": "getR3", "login": self._login})) data = r.json() self._R3 = data["R3"] m = hashlib.sha256() m.update(int_to_bytes(self._password)) m.update(int_to_bytes(self._R3)) password = m.digest() password = bytes_to_int(password) data = requests.post(SERVER_ADDR, data=json.dumps( {"type": "send", "login": self._login, "password": self._password, "user": user, "message": message})).json() if data["error"] != "OK": print(data["error"]) return self._R3 = data["R3"]
def content(self): qname, cur = parse_domain(self.bmsg, self.offset) qtype = bytes_to_int(self.bmsg[cur: cur + 2]) qclass = bytes_to_int(self.bmsg[cur + 2: cur + 4]) cur += 4 num_bytes = cur return qname, qtype, qclass, num_bytes
def parse_misc_events(self, fp): try: param1 = fp.read(1) param2 = fp.read(1) except: raise IOError("Couldn't read MIDI event parameters from file.") self.param1 = utils.bytes_to_int(param1) self.param2 = utils.bytes_to_int(param2) return 2
def ip_network(self): if self.afi == 1: ip = IPv4Address(Bytes(self.value[:4])) ipnet = IPv4Network( str(ip) + '/' + str(bytes_to_int(self.value[4]))) else: ip = IPv6Address(Bytes(self.value[:16])) ipnet = IPv6Network( str(ip) + '/' + str(bytes_to_int(self.value[16]))) return IPNetwork(str(ipnet))
def parse_domain(bmsg: bytes, cur: int): qname = [] while True: if bmsg[cur] == bytes_to_int(b'\xc0'): cur = bytes_to_int(bmsg[cur: cur + 2]) - bytes_to_int(b'\xc0\x00') label_len = bmsg[cur] if label_len == 0: break qname.append(bmsg[cur + 1: cur + label_len + 1].decode()) cur += label_len + 1 cur += 1 return '.'.join(qname), cur
def set_locator(self, locator): self.locator = {} l = [None] * 2 for i in range(0, len(locator), 4): afi = bytes_to_int(locator[i]) ip = ipaddr_to_netaddr(afi, locator[i + 1]) priority = bytes_to_int(locator[i + 2]) weight = bytes_to_int(locator[i + 3]) l[0] = priority l[1] = weight self.locator[ip] = l self.map_server = {}
def autorize(self, passwor = None, logi = None): self._authorized = False r = requests.post(SERVER_ADDR, data=json.dumps({"type": "getR2"})) data = r.json() self._R2 = data["R2"] if logi is None: print("write your login pls") print(">> ", end='') self._login = input().strip() else: self._login = logi r = requests.post(SERVER_ADDR, data=json.dumps({"type": "getR3", "login": self._login})) data = r.json() self._R3 = data["R3"] password = "" if passwor is None: print("enter password") print(">> ", end='') password = input().strip() else: password = passwor m = hashlib.sha256() m.update(bytes(password, 'utf-8')) m.update(int_to_bytes(self._R2)) password = m.digest() password = bytes_to_int(password) self._password = password m = hashlib.sha256() m.update(int_to_bytes(password)) m.update(int_to_bytes(self._R3)) password = m.digest() password = bytes_to_int(password) data = (requests.post(SERVER_ADDR, data=json.dumps({"type": "autorize", "login": self._login, "password": password}))).json() if (data["error"] == "password_error"): print("wrong password") elif (data["error"] == "OK"): print("correct password") self._R3 = data["R3"] r = requests.post(SERVER_ADDR, data=json.dumps({"type": "getpg"})) data = r.json() self._p = data["p"] self._g = data["g"] self._authorized = True elif (data["error"] == "login_error" ): raise RuntimeError("login_error") else: print("some error")
def register(self, logi = "", passwor = ""): r = requests.post(SERVER_ADDR, data=json.dumps({"type": "getR2"})) data = r.json() self._R2 = data["R2"] if not logi: print("write your login pls") print(">> ", end='') self._login = input().strip() else: self._login = logi if not passwor: print("enter password") print(">> ", end='') password = input().strip() else: password = passwor m = hashlib.sha256() m.update(bytes(password, 'utf-8')) m.update(int_to_bytes(self._R2)) password = m.digest() password = bytes_to_int(password) data = (requests.post(SERVER_ADDR, data=json.dumps({"type": "register", "login": self._login, "password": password}))) print(data) data = data.json() while (data["error"] == "accupied"): print("choose another login pls") print(">> ", end='') self._login = input().strip() data = (requests.post(SERVER_ADDR, data=json.dumps( {"type": "register", "login": self._login, "password": password}))).json() print("succefful registration") self._password = password
def parse_midi_event(self, fp): """Parse a MIDI event. Return a dictionary and the number of bytes read. """ self.reset() chunk_size = 0 try: ec = utils.bytes_to_int(fp.read(1)) chunk_size += 1 except: raise IOError("Couldn't read event type " "and channel data from file.") # Get the nibbles event_type = (ec & 0xf0) >> 4 channel = ec & 0x0f # I don't know what these events are supposed to do, but I keep finding # them. The parser ignores them. if event_type < 8: #sys.stderr.write('WARN: Unknown event type %d.\n' % event_type) return chunk_size self.event_type = event_type self.channel = channel if event_type == 0x0f: chunk_size += self.parse_meta_event(fp) elif event_type in [12, 13]: chunk_size += self.parse_program_change_and_channel_aftertouch_events(fp) else: chunk_size += self.parse_misc_events(fp) return chunk_size
def parse_program_change_and_channel_aftertouch_events(self, fp): try: param1 = fp.read(1) except: raise IOError("Couldn't read MIDI event parameters from file.") self.param1 = utils.bytes_to_int(param1) return 1
def __init__(self, bmsg, offset): super(DNSAnswer, self).__init__() self.bmsg = bytearray(bmsg) self.offset = offset assert self.bmsg[self.offset] >= bytes_to_int(b'\xc0') self.len_name = 2 self.next_offset = self.offset + self.len_name + 10 + self.rdlength
def compress(self, write_obj, data_only=False): """write_obj is a binary writable object. If data_only is set to True then only the compressed data will be written. Otherwise it will also write meta information at the start of the stream.""" if not data_only: self.write_meta(write_obj) temp_byte = int(0) # cannot bit shift a bytes object directly temp_bits_written = 0 for word in self.file: word_compressed = self.encode_dict[bytes_to_int(word)] word_compressed_length = len(word_compressed) comp_word_index = 0 for comp_word_index in range(word_compressed_length): #while comp_word_index < word_compressed_length: if word_compressed[comp_word_index] == "1": temp_byte += 1 temp_bits_written += 1 if temp_bits_written == 8: write_obj.write(temp_byte.to_bytes(1, "big", signed=False)) temp_byte = 0 temp_bits_written = 0 else: temp_byte = temp_byte << 1 if temp_bits_written != 0: temp_byte = temp_byte << (8 - temp_bits_written - 1) write_obj.write(temp_byte.to_bytes(1, "big", signed=False)) write_obj.seek(0)
def deserialize_amount(self): t = utils.bytes_to_int(self.get_bytes(8)) if (t >> 63) == 1: positive = (t >> 62) & 1 exponent = ((t >> 54) & 255) - 97 value = str(t & ((1 << 54) - 1)) if value != '0': decimal = Decimal((positive ^ 1, tuple(map(int, value)), exponent)) value = _clean_up(str(decimal)) currency = self.deserialize_currency() issuer = self.deserialize_account_id() return { 'value': value, 'currency': currency, 'issuer': issuer } else: positive = t >> 62 value = t & ((1 << 62) - 1) value = value if positive else -value return str(value)
def load_prg_rom(self, data_prgrom: bytes): # 暂时实现16kb self.space[0x8000:0xC000] = data_prgrom[:16384] self.space[0xC000:] = data_prgrom[-16384:] # 加载PC start_index = bytes_to_int(self.space[0xFFFC:0xFFFC + 2]) self.PC = start_index self.space[0x2002] = 0b10100000
def transverse(node, encode_dict, collected): if node.content is not None: encode_dict[bytes_to_int(node.content)] = collected else: if node.rchild is not None: transverse(node.rchild, encode_dict, collected + "1") if node.lchild is not None: transverse(node.lchild, encode_dict, collected + "0")
def set_map_server(self, map_server): self.map_server = {} for i in range(0, len(map_server), 3): afi = bytes_to_int(map_server[i]) ip = ipaddr_to_netaddr(afi, map_server[i + 1]) address = map_server[i + 2] self.map_server[ip] = address self.locator = {}
def read(self): ''' Read the raw data from the sensor, scale it appropriately and store for later use ''' raw_gyro_data = self.i2c.read_reg_block(self.address, MPU6050_GYRO_START_BLOCK) raw_accel_data = self.i2c.read_reg_block(self.address, MPU6050_ACCEL_START_BLOCK) raw_temp_data = self.i2c.read_reg_block(self.address, MPU6050_TEMP_START_BLOCK) self.gyro_raw_x = bytes_to_int(raw_gyro_data[MPU6050_GYRO_XOUT_H], raw_gyro_data[MPU6050_GYRO_XOUT_L]) self.gyro_raw_y = bytes_to_int(raw_gyro_data[MPU6050_GYRO_YOUT_H], raw_gyro_data[MPU6050_GYRO_YOUT_L]) self.gyro_raw_z = bytes_to_int(raw_gyro_data[MPU6050_GYRO_ZOUT_H], raw_gyro_data[MPU6050_GYRO_ZOUT_L]) self.accel_raw_x = bytes_to_int(raw_accel_data[MPU6050_ACCEL_XOUT_H], raw_accel_data[MPU6050_ACCEL_XOUT_L]) self.accel_raw_y = bytes_to_int(raw_accel_data[MPU6050_ACCEL_YOUT_H], raw_accel_data[MPU6050_ACCEL_YOUT_L]) self.accel_raw_z = bytes_to_int(raw_accel_data[MPU6050_ACCEL_ZOUT_H], raw_accel_data[MPU6050_ACCEL_ZOUT_L]) self.raw_temp = bytes_to_int(raw_temp_data[MPU6050_TEMP_OUT_H], raw_temp_data[MPU6050_TEMP_OUT_L]) # We convert these to radians for consistency and so we can easily combine later in the filter self.gyro_x = math.radians(self.gyro_raw_x / MPU6050_GYRO_SCALE[self.fs_scale][1]) - self.gyro_x_offset self.gyro_y = math.radians(self.gyro_raw_y / MPU6050_GYRO_SCALE[self.fs_scale][1]) - self.gyro_y_offset self.gyro_z = math.radians(self.gyro_raw_z / MPU6050_GYRO_SCALE[self.fs_scale][1]) - self.gyro_z_offset self.accel_x = self.accel_raw_x / MPU6050_ACCEL_SCALE[self.afs_scale][1] self.accel_y = self.accel_raw_y / MPU6050_ACCEL_SCALE[self.afs_scale][1] self.accel_z = self.accel_raw_z / MPU6050_ACCEL_SCALE[self.afs_scale][1] self.temp = self.raw_temp / 340 + 36.53
def recv_message(self): m = hashlib.sha256() m.update(int_to_bytes(self._password)) m.update(int_to_bytes(self._R3)) password = m.digest() password = bytes_to_int(password) data = requests.post(SERVER_ADDR, data=json.dumps({"type": "recv", "login": self._login, "password": password})).json() if data["error"] != "OK": r = requests.post(SERVER_ADDR, data=json.dumps({"type": "getR3", "login": self._login})) data = r.json() self._R3 = data["R3"] m = hashlib.sha256() m.update(int_to_bytes(self._password)) m.update(int_to_bytes(self._R3)) password = m.digest() password = bytes_to_int(password) data = requests.post(SERVER_ADDR, data=json.dumps({"type": "recv", "login": self._login, "password": password})).json() if data["error"] != "OK": print(data["error"]) return self._R3 = data["R3"] if (data["message"].strip()): m = re.match( r"\s*(?P<name>\S+):\s*razrabotchyk_pidor90585355972355049027130019104418304977474815248020730362080159511218759452819\s+(?P<text>\d*)", data["message"].strip()) m2 = re.match(r"\s*(?P<name>\S+):\s*(?P<text>.*)", data["message"].strip()) if m: user = m.group("name") self._B[user] = int(m.group("text")) if not self._A.get(user): self.diffi_with_user(user) self._K[user] = fast_power(self._B[user], self._a[user], self._p) elif m2 and self._K.get(m2.group("name")): user = m2.group("name") text = m2.group("text") msg = b64decode(text) msg_nonce = msg[:8] ciphertext = msg[8:] cipher = Salsa20.new(key=int_to_bytes(self._K[user])[-32:], nonce=msg_nonce) plaintext = cipher.decrypt(ciphertext) print(user + ":_ ", plaintext.decode('utf-8')) else: print(data["message"].strip()) # fixme good enough for demo lol( 1 message per second)
def decrypt(crypto_data, data_to_decrypt): decrypted_data = PyCryptodomeAESModule.new( crypto_data.encryption_hash, PyCryptodomeAESModule.MODE_CBC, iv=crypto_data.iv).decrypt(data_to_decrypt) crypto_data.iv_is_from_deserializer = False # Not exactly true... It's a bad variable name. but basically we assume that since the IV has been used once, it can be overwritten return decrypted_data[0:utils.bytes_to_int( crypto_data.data_length )] # Remove the padding using the stored data length
def test_rng_2(self): checksum = bytes_to_int(crc32_bytes(string_to_bytes("Wolf"))) rng = Xoshiro256.from_crc32(checksum) numbers = [] for i in range(100): numbers.append(rng.next() % 100) expected_numbers = [88, 44, 94, 74, 0, 99, 7, 77, 68, 35, 47, 78, 19, 21, 50, 15, 42, 36, 91, 11, 85, 39, 64, 22, 57, 11, 25, 12, 1, 91, 17, 75, 29, 47, 88, 11, 68, 58, 27, 65, 21, 54, 47, 54, 73, 83, 23, 58, 75, 27, 26, 15, 60, 36, 30, 21, 55, 57, 77, 76, 75, 47, 53, 76, 9, 91, 14, 69, 3, 95, 11, 73, 20, 99, 68, 61, 3, 98, 36, 98, 56, 65, 14, 80, 74, 57, 63, 68, 51, 56, 24, 39, 53, 80, 57, 51, 81, 3, 1, 30] assert(numbers == expected_numbers)
def get_public_key(private_key): ''' Gets the public key from the private key. Params: - private_key (bytes): The private key Returns (bytes): The public key corrisponding the private key. ''' secexp = bytes_to_int(private_key) sk = ecdsa.SigningKey.from_secret_exponent(secexp) vk = sk.get_verifying_key() return vk.to_string()
def stack_pop(self, size=1): # S其实是个偏移量,栈空间存从第一页开始 s = self.S + 256 if size == 1: value = self.space[s + 1] if size == 2: bs = self.space[s + 1:s + 3] value = bytes_to_int(bs) self.S += size return value
def parse_meta_event(self, fp): meta_event = utils.bytes_to_int(fp.read(1)) (length, chunk_delta) = utils.parse_varbyte_as_int(fp) if meta_event == 0x2f: self.last_event_of_track = True data = fp.read(length) chunk_size = 1 + chunk_delta + length self.meta_event = meta_event self.data = data return chunk_size
def test_tx_hash_with_extra_nonce(self): inputs = [Bytes(b"one"), Bytes(b"two"), Bytes(b"three")] outputs = [Bytes(b"abc"), Bytes(b"xyz")] tx = blockchain.Transaction(inputs=inputs, outputs=outputs, hash_f=lambda x: b"(" + x + b")") tx.extra_nonce = bytes_to_int(bytes("X".encode("utf-8"))) assert b"(onetwothreeabcxyzX)" == tx.hash
def NMI(self): # 即要等到这次 NMI 执行结束之后,才能引起下一次 NMI # self.space[0x2000][7] = 0 # 这个不是汇编指令,但暂时也放在这里。 self.stack_push(self.PC, size=2) P = copy.copy(self.registers['P']) P[4] = 0 p = P.flag self.stack_push(p) pc_bytes = self.space[self.NMI_AD:self.NMI_AD + 2] pc = bytes_to_int(pc_bytes) self.PC = pc
def details(self): return self.summary + \ "Hash (bin) : {:}\n" \ "Hash (hex) : {:}\n" \ "Nonce : {:010d}\n" \ "Extra-nonce : {:010d}\n" \ "Merkle root : {:}\n" \ .format( bin_str(bytes_to_int(self.hash), pad=service.hash_f.bits), bin_to_hex(self.hash), self.nonce, self.extra_nonce, bin_to_hex(self.merkle_root) )
def video_extract(self): ''' seperate the .h264 video from the flv video ''' current = self._bytes_begin while current < self._size: tag_type = self._flv_data[current] tag_data_size = bytes_to_int(self._flv_data[current + 1:current + 4]) tag_data = self._flv_data[current + 11:current + 11 + tag_data_size] if tag_type == VIDEO: if tag_data[0] == 0x17 and tag_data[1] == 0x00: self._video_tag_header = video_tag_header(tag_data) self._h264_data += b"\x00\x00\x00\x01" + self._video_tag_header.sps_data + b"\x00\x00\x00\x01" + self._video_tag_header.pps_data # assert the video only have one sps and one pps else: assert ((tag_data[0] & 0xf) == 7) #assert for avc only if tag_data[1] == 0x1: nalu_length = bytes_to_int(tag_data[5:9]) begin = 9 if begin + nalu_length == tag_data_size: self._h264_data += b"\x00\x00\x00\x01" + tag_data[ 9:] else: while True: self._h264_data += b"\x00\x00\x00\x01" + tag_data[ begin:begin + nalu_length] begin += nalu_length if begin == tag_data_size: break nalu_length = bytes_to_int( tag_data[begin:begin + 4]) begin += 4 current += 11 + tag_data_size assert (bytes_to_int(self._flv_data[current:current + 4]) == 11 + tag_data_size) current += 4
def mine_one_iteration(self, block: blockchain.Block): """ Perform one iteration of block mining (increments the nonce once) """ found, nonce, curr_hash = block.mine_one() sys.stdout.write("Nonce: {:010d} | Hash : {:}\r".format( nonce, bin_str(bytes_to_int(curr_hash), pad=service.hash_f.bits))) if found: console.info("Found a new block:" + " " * 32 + "\n{:}\n".format(block.details)) self.maybe_add_block(block) self._hash_prev = block.hash return found
def test_NMI(): cpu = Cpu() nes = load_nes() prg_rom = nes['prg_rom'] cpu.load_prg_rom(prg_rom) cpu.load_chr_rom(nes['chr_rom']) NMI_AD = 0xFFFA save_p = 0b11111111 cpu.registers['P'].flag = save_p right_pc = bytes_to_int(cpu.space[NMI_AD:NMI_AD + 2]) log(cpu.registers) cpu.NMI() log(cpu.registers) assert cpu.PC == right_pc # P 4位置0后压入stack s = cpu.registers['S'] pushed_p = cpu.space[s + 256 + 1] assert pushed_p == 0b11101111
def mine_one(self): # Increment extra nonce if nonce overflows and update merkle tree if self._nonce == 0 or self._nonce >= 2**32 - 1: self.extra_nonce += 1 self._nonce = 0 self.update_merkle_tree() # Calculate hash with current nonce and extra_nonce curr_hash = service.hash_f(self._bytes + int_to_bytes(self._nonce)) # If target is meet, we found the nonce if bytes_to_int(curr_hash) < self.target: self._hash = curr_hash return True, self._nonce, self._hash # If target is not met proceed with the next nonce on next call self._nonce += 1 return False, self._nonce, curr_hash
def to_dict(self): d = {} for name, _ in self.__class__.fields: d[name] = getattr(self, name) if name in ('to', ): d[name] = '0x' + encode_hex(d[name]) elif name in ('value', ): if self.afi == 1: ip = IPv4Address(Bytes(d[name][:4])) net = IPv4Network( str(ip) + '/' + str(bytes_to_int(d[name][4]))) d[name] = str(net) else: ip = IPv6Address(Bytes(d[name][:16])) net = IPv6Network( str(ip) + '/' + str(bytes_to_int(d[name][16]))) d[name] = str(net) elif name in ('metadata', ) and self.category == 2: _metadata = [] i = 0 while i < len(d[name]): _metadata.append(bytes_to_int(d[name][i])) if _metadata[-1] == 1: ip = IPv4Address(Bytes(d[name][i + 1])) else: ip = IPv6Address(Bytes(d[name][i + 1])) _metadata.append(str(ip)) _metadata.append(encode_hex(d[name][i + 2])) i += 3 d[name] = _metadata elif name in ('metadata', ) and self.category == 3: _metadata = [] i = 0 while i < len(d[name]): _metadata.append(bytes_to_int(d[name][i])) if _metadata[-1] == 1: ip = IPv4Address(Bytes(d[name][i + 1])) else: ip = IPv6Address(Bytes(d[name][i + 1])) _metadata.append(str(ip)) _metadata.append(bytes_to_int(d[name][i + 2])) _metadata.append(bytes_to_int(d[name][i + 3])) i += 4 d[name] = _metadata d['sender'] = '0x' + encode_hex(self.sender) d['hash'] = '0x' + encode_hex(self.hash) return d
def eval_ad(self): ad_type = self.ad_type size = self.sizes[ad_type] ad_args = self.space[self.PC + 1:self.PC + size] if ad_type == 'ABS': # 绝对地址 cur_ad = bytes_to_int(ad_args) elif ad_type == 'IMM': # 直接赋值 cur_ad供log用 cur_ad = bytes_to_int(ad_args) self._cur_value = cur_ad elif ad_type == 'ZPG': # 零页地址 cur_ad = bytes_to_int(ad_args) elif ad_type == 'IMP': # 内部定义,不需要外部值 cur_ad = -1 elif ad_type == 'REL': # 间接地址 需要正负号 考虑地址溢出 offset = bytes_to_int(ad_args, signed=True) size = self.sizes[self.ad_type] ad = self.PC + size + offset & 0xffff cur_ad = ad # value = self.space[cur_ad] elif ad_type == 'ABX': # 考虑地址溢出 y = self.X base_ad = bytes_to_int(ad_args) cur_ad = (base_ad + y) & 0xffff # value = self.space[cur_ad] elif ad_type == 'ABY': # 考虑 地址溢出 y = self.Y base_ad = bytes_to_int(ad_args) cur_ad = (base_ad + y) % 65536 # value = self.space[cur_ad] elif ad_type == 'ZPX': # 考虑零页溢出 offset = bytes_to_int(ad_args) cur_ad = (self.X + offset) % 256 # value = self.space[cur_ad] elif ad_type == 'ZPY': # 考虑零页溢出 offset = bytes_to_int(ad_args) cur_ad = (self.Y + offset) % 256 elif ad_type == 'INX': # 间接系列,存在bug. order ($xxFF)无法正常工作. base_ad = (ad_args[0] + self.X) & 0xff low = (base_ad) & 0xff high = (base_ad + 1) & 0xff real_ad = [self.space[low], self.space[high]] cur_ad = bytes_to_int(real_ad) elif ad_type == 'INY': # 间接系列,存在bug. order ($xxFF)无法正常工作. base_ad = ad_args[0] if base_ad % 256 == 255: real_ad = [self.space[base_ad], self.space[base_ad - 255]] else: real_ad = self.space[base_ad:base_ad + 2] cur_ad = (bytes_to_int(real_ad) + self.Y) % 65536 # value = self.space[cur_ad] elif ad_type == 'IND': # 间接系列,存在bug. order ($xxFF)无法正常工作. base_ad = bytes_to_int(ad_args) if base_ad % 256 == 255: real_ad = [self.space[base_ad], self.space[base_ad - 255]] else: real_ad = self.space[base_ad:base_ad + 2] cur_ad = bytes_to_int(real_ad) else: print('未实现的寻址', ad_type) raise Exception('未实现的寻址', ad_type) self.cur_ad = cur_ad
def deserialize_int16(self): return utils.bytes_to_int(self.get_bytes(2))
def encode(self, v): p = zero_padding(v) t = utils.bytes_to_int(v) v = utils.int_to_bytes(t, BASE) return xlate(p + v, self.fwd)
def decode(self, v): v = xlate(v, self.inv) p = zero_padding(v) t = utils.bytes_to_int(v, BASE) v = utils.int_to_bytes(t) return p + v
def deserialize_int32(self): return utils.bytes_to_int(self.get_bytes(4))