from Device import Codec import time class Compiler: def __init__(self, codes, filename='a.out'): self.filename = filename self.data = [] for i in codes: self.data.append(Codec.str2int(i)) self.write() def write(self): # 打开文件,以二进制写入模式打开 with open(self.filename, 'wb') as f: maxNum = max(self.data) byte_representation = (maxNum.bit_length() + 7) // 8 if byte_representation > 139: raise MemoryError() # 写入整数数据 f.write(b'\x5a\xe3'+byte_representation.to_bytes(1, 'little')) for num in self.data: # 将整数转换为字节,并写入文件 f.write(num.to_bytes(byte_representation , 'little')) # 假设每个整数都用4个字节表示 def read(self): int_data_read = [] # 用于存储读取的整数数据 # 打开文件,以二进制读取模式打开 with open(self.filename, 'rb') as f: # 读取整数数据 MagicNumber = f.read(2) size = int.from_bytes(f.read(1), 'little') while True: # 从文件中读取4个字节,并将其转换为整数 int_bytes = f.read(size) if not int_bytes: # 如果读取完整个文件,则退出循环 break int_value = int.from_bytes(int_bytes, 'little') # 假设之前用little-endian序列化 int_value = Codec.int2list(int_value) int_value = Codec.int2str(int_value) int_data_read.append(int_value) return int_data_read start = time.time() c = Compiler(["l","h",'kakshdhsh sjjsvav']) print(time.time()-start) print(list(c.read()))