I'm writing the Assembler in Python. So far, I have a Translate() function that can successfully translate a single command into binary:
# Function that turns an A command into a binary value
def Acommand(input):
input = input[1:]
integer = int(input)
output = str(bin(integer)[2:])
while len(output)<16:
output = "0" + output
return output
#Function that translates a C command into binary instruction
def Ccommand(input):
output="111"
dest = ""
jump = ""
IsDest = False
IsJump = False
if "=" in input: #Checks if there's a destination component
equals = input.index("=")
dest = input[:equals]
input = input[(equals + 1):]
IsDest = True
if ";" in input: #Checks if there's a jump component
semicolon = input.index(";")
jump = input[(semicolon + 1):]
input = input[:semicolon]
IsJump = True
if "M" in input: #Adds 'a' bit
output = output + "1"
else:
output = output + "0"
for comp_instruction in comp_table: #Adds comp bits
if input == comp_instruction:
output = output + comp_table[comp_instruction]
break
if IsDest: #Adds dest bits
for dest_instruction in dest_table:
if dest == dest_instruction:
output = output + dest_table[dest_instruction]
break
else:
output = output + "000"
if IsJump: #Adds jump bits
for jump_instruction in jump_table:
if jump == jump_instruction:
output = output + jump_table[jump_instruction]
break
else:
output = output + "000"
return output
# Checks if input is A or C instruction, then calls appropriate function
def Translate(input):
if "@" in input:
return Acommand(input)
else:
return Ccommand(input)
Now I'm trying to iterate through the lines of a source file and call the Translate() function for each one, writing the result to a destination file. Code looks like this:
import Assembler
source = open("source.txt", "r")
dest = open("destination.txt", "a")
for line in source:
dest.write(Assembler.Translate(line) + "\n")
source.close()
dest.close()
The output is very strange: all the A commands are correctly translated into binary, but the C commands are only between 10 and 13 bits in length! I don't understand what's going on, because if the problem was with the Translate() function, it shouldn't work when individual C commands are plugged in, but if the problem is with the for loop, it shouldn't work for the A commands. What am I missing?