【问题标题】:Python "local variable 'pc' referenced before assignment" issue in basic decomplier基本反编译器中的Python“赋值前引用的局部变量'c'”问题
【发布时间】:2025-11-27 03:55:01
【问题描述】:

我和一个朋友正在努力创建一个基本的概念验证反编译器,它接受一串十六进制值并返回一个更易读的版本。我们的代码如下所示

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 是一个全局变量,它不应该在任何地方都可以使用吗?感谢您提供任何和所有帮助 - 如果您发现其他错误,请随时发表评论指出它们!

【问题讨论】:

    标签: python string variables hex emulation


    【解决方案1】:

    最近经常看到这个。当你这样做时

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

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

    global pc
    

    【讨论】: