基本反编译器中的 Python "local variable 'pc' referenced before assignment"问题



和一位朋友正在努力创建一个基本的概念验证反编译器,该编译器采用一串十六进制值并返回更具可读性的版本。我们的代码列在下面

testProgram = "00 00 FF 55 47 00"
# should look like this
# NOP
# NOP
# MOV 55 47
# NOP
pc = 0
output = ""
def byte(int):
    return testProgram[3 * int:3 * int + 2]
def interpret():
    currentByte = byte(pc)
    if currentByte == "00":
        pc += 1
        return "NOP"
    if currentByte == "FF":
        returner = "MOV " + byte(pc + 1) + " " + byte(pc + 2)
        pc += 3
        return returner
while(byte(pc) != ""):
    output += interpret() + "n"
print(output)

但是,运行代码告诉我们这一点

Traceback (most recent call last):
  File "BasicTest.py", line 62, in <module>
    output += interpret() + "n"
  File "BasicTest.py", line 50, in interpret
    currentByte = byte(pc)
UnboundLocalError: local variable 'pc' referenced before assignment

因为 pc 是一个全局变量,它不应该在任何地方使用吗?任何和所有的帮助都是值得赞赏的 - 如果您发现其他错误,请随时发表评论指出它们!

最近经常

看到这个。当你这样做时

if currentByte == "00":
    pc += 1  # <----------
    return "NOP"

您正在分配给局部变量 pc ,但尚未在局部范围内声明pc。如果要修改全局pc则需要在函数顶部显式声明

global pc

最新更新