Python学习 - 冯诺伊曼体系结构建模与模拟 之TOY模型机

mem = [0] * 1000  # 主存
reg = [0] * 10  # 通用寄存器
pReg = 0  # 程序计数器
iReg = 0  # 指令寄存器
res = 0  # 存放输出结果

# 加载TOY2程序
def loadProgram(file):
    global pReg, iReg, reg, mem  # 全局变量声明
    # *********** Begin **********#
    # 打开文件
    fil = open(file)
    # 用于标识是否为第1条指令
    first = True
    while True:  # 每循环一次加载一条指令
        # 读1行
        line = fil.readline()
        if line == '':  # 若读取完毕,则结束循环
            break
        # 将1行拆分为若干部分
        flds = line.split()
        # 第0部分为地址
        address = int(flds[0])
        # 第1部分为指令
        instruc = flds[1]
        # 将指令加载到主存单元
        mem[address] = instruc
        if first == True:  # 若是第1条指令
            pReg = address  # 则将其地址存入程序寄存器
            first = False  # 后面的指令不再是第1条指令
    fil.close()  # 关闭文件


# 执行一条TOY2指令
def cycle():
    global pReg, iReg, reg, mem, res

    # 取指令,根据pReg的值,将指令从mem取到iReg
    iReg = int(mem[pReg])
    # pReg加1,指向下一条指令
    pReg = pReg + 1
    # 译码
    opcode = iReg // 10000  # 操作码
    op1 = (iReg // 1000) % 10  # 操作数1
    op2 = iReg % 1000  # 操作数2
    # 执行和写结果
    if opcode == 0:  # 停止指令
        return False
    elif opcode == 1:  # 数据移动指令:寄存器←主存
        reg[op1] = mem[op2]
    elif opcode == 2:  # 数据移动指令:主存←寄存器
        mem[op1] = reg[op2]
    elif opcode == 3:  # 数据移动指令:寄存器←数字
        reg[op1] = op2
    elif opcode == 4:  # 加法指令
        reg[op1] = reg[op1] + reg[op2]
    elif opcode == 5:  # 减法指令
        reg[op1] = reg[op1] - reg[op2]
    elif opcode == 6:  # 乘法指令
        reg[op1] = reg[op1] * reg[op2]
    elif opcode == 7:  # 除法指令
        reg[op1] = reg[op1] / reg[op2]
    elif opcode == 8:  # 无条件跳转指令
        pReg = op2
    elif opcode == 9:  # 条件跳转指令
        if reg[op1] == 0:
            pReg = op2
    elif opcode == 10:  # 输入指令
        reg[op1] = int(input('input:'))
    elif opcode == 11:  # 输出指令
        res = reg[op1]
        print('output:', reg[op1])
    return True
    # *********** End **********#


def run(file):
    global pReg, iReg, reg, mem
    loadProgram(file)  # 加载TOY2程序

    while True:  # 每循环一次,执行一条指令
        hasNextInstruc = cycle()  # 执行一条TOY2指令
        if hasNextInstruc == False:  # 若执行的是停机指令
            break  # 则跳出循环
    return res

result1 = run('./step1/add.toy2.txt') #运行add.toy2中的TOY2程序
result2 = run('./step1/sum100.toy2.txt')#运行sum100.toy2中的TOY2程序
if result1 == 25 and result2 == 5050:
    print("你的程序正确!!!")
else:
    print("你的程序错啦!!!")

 add.toy2

000   031012
001   032013
002   041002
003   111000
004   000000

sum100.toy2

000   031000
001   032001
002   033001
003   041002
004   042003
005   034101
006   054002
007   094009
008   080003
009   111000
010   000000
  • 10
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值