Whenever I am trying to run this code
def BinToHex(x):
a = hex(int(x,2))
return a[2:]
def HexToBin(x):
b = bin(int(x,16))[2:]
return b
c = 0
with open("input.txt") as l:
for line in l:
c += 1
l.close()
x = ""
def main():
Write = open("binary.txt","w")
Read = open("input.txt", "r")
for i in range(c):
bakwaas = Read.readline()
d = bakwaas.split()
opcode = d[0]
address = d[1]
li = {"cla":"7800","cma":"7400","inc":"7200","hlt":"7100","inp":"f800","out":"f400","ski":"f200","sko":"f100","ion":"f080","iof":"f040"}
la = {"and":"000","lda":"010","add":"001","sta":"011","bun":"100","call":"101","sub":"110"}
if opcode in li:
u = li[opcode]
hexaNum1 = HexToBin(u)
if len(hexaNum1) == 16:
hexaNum1 = hexaNum1
else:
hexaNum1 = "0" + hexaNum1
Write.write(hexaNum1)
x += hexaNum1
Write.write("\n")
else:
hexaNum2 = address[:3]
arr = opcode[:3]
ad = la[arr]
if opcode[-1]=="#":
ad = "0" + ad
elif opcode[-1]=="@":
ad = "1" + ad
temp = ad
bintemp = HexToBin(hexaNum2)
hextemp = BinToHex(ad)
ad = hextemp + bintemp
temp = "000" + temp + bintemp
Write.write(temp)
x += temp
Write.write("\n")
Write.close()
Read.close()
String = x
BitInString = [String[i:i + 8] for i in range(0, len(String), 8)]
BytesInString = [int(i,2) for i in BitInString]
with open("output.bin", "wb") as l:
l.write(bytearray(BytesInString))
l.close()
main()
Traceback (most recent call last): File "exercise.py", line 63, in main() File "exercise.py", line 51, in main x += temp UnboundLocalError: local variable 'x' referenced before assignment
I was assigned an assignment to recreate assembler which can read Machine language in a higher language of our choice. So, I am reading the code content from text and reading as well as writing in a binary file.
my text file contains and@ 123
as for the output I should be getting a file with a size of 2 bytes and 0001000100100011 in a binary file according to my input. I am not able to understand what is this error trying to tell me.