import re regmap = { 'zero': 0, 'at': 1, 'v0': 2, 'v1': 3, 'a0': 4, 'a1': 5, 'a2': 6,…
- User
import re
reg_map = { 'zero': 0, 'at': 1, 'v0': 2, 'v1': 3, 'a0': 4, 'a1': 5, 'a2': 6, 'a3': 7, 't0': 8, 't1': 9, 't2': 10, 't3': 11, 't4': 12, 't5': 13, 't6': 14, 't7': 15, 's0': 16, 's1':17, 's2':18, 's3':19, 's4':20, 's5':21, 's6':22, 's7':23, 't8':24, 't9':25, 'k0':26, 'k1':27, 'gp':28, 'sp':29, 'fp':30, 'ra':31 }
def get_register_number(reg_name): reg_name = reg_name.strip().lstrip('') if reg_name.isdigit(): # For registers like 0 - $31 return int(reg_name) elif reg_name in reg_map: return reg_map[reg_name] else: raise ValueError(f"Unknown register name {reg_name}")
def get_register_name(num): for name, n in reg_map.items(): if n == num: return name raise ValueError(f"Unknown register number {num}")
def read_asm_file(file_path): with open(file_path, 'r') as file: lines = file.readlines() # Remove comments and empty lines instructions = [] for line in lines: line = re.sub(r'#.*', '', line).strip() if line: instructions.append(line) return instructions
def parse_labels_and_instructions(instructions): labels = {} parsed_instructions = [] pc = 0 data_mode = False memory = {} current_address = 0x10010000 # Starting address for data section
for line in instructions: if line.startswith(".data"): data_mode = True continue elif line.startswith(".text"): data_mode = False pc = 0 continue if data_mode: if ':' in line: label, line_part = line.split(':', 1) labels[label.strip()] = current_address line = line_part.strip() if line.startswith('.word'): line = line.replace('.word', '').strip() values = line.split(',') for value in values: memory[current_address] = int(value) current_address += 4 elif line.startswith('.asciiz'): line = line.replace('.asciiz', '').strip().strip('"') for char in line: memory[current_address] = ord(char) current_address += 1 memory[current_address] = 0 # Null-terminate the string current_address += 1 else: if ':' in line: label, line_part = line.split(':', 1) labels[label.strip()] = pc line = line_part.strip() if line: parsed_instructions.append(line) pc += 4 return parsed_instructions, labels, memorydef convert_to_binary(instruction, labels, current_pc): opcodes = { "addi": "001000", "andi": "001100", "ori": "001101", "beq": "000100", "bne": "000101", "j": "000010", "jal": "000011", "lw": "100011", "sw": "101011", "lui": "001111", "and": "000000", "or": "000000", "slt": "000000", "add": "000000", "sub": "000000", "mul": "011100", # Special MIPS opcode for multiplication "sll": "000000", "srl": "000000", "jr": "000000", "xor": "000000", "nor": "000000", "syscall": "000000", } functs = { "and": "100100", "or": "100101", "slt": "101010", "add": "100000", "sub": "100010", "mul": "000010", # Function code for mul "sll": "000000", "srl": "000010", "jr": "001000", "xor": "100110", "nor": "100111", "syscall": "001100" }
- Assistant