每当我尝试运行此代码
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()
回溯(最近一次通话最后一次):文件“ exercise.py”,第63行,在 main()在main中的第51行,文件“ exercise.py” x + = temp UnboundLocalError:赋值之前引用了本地变量'x'
我被分配了一个重新创建汇编器的任务,该汇编器可以用我们选择的更高语言来阅读机器语言。因此,我正在从文本中读取代码内容并进行读取以及写入二进制文件。
我的文本文件包含 和@ 123
对于输出,我应该根据我的输入在二进制文件中得到一个2字节大小和0001000100100011的文件。 我无法理解此错误试图告诉我什么。
答案 0 :(得分:0)
x += hexaNum1
转换为x = x + hexaNum1
(与x += temp
相同),因此需要在操作之前定义x
,否则它将不知道要添加哪个值。
您可以通过在x = 0
循环之前添加for
来轻松解决此问题(前提是您希望x
的起始值为默认的整数0
)