选项卡中的Python编码信息

2024-05-29 04:45:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用python处理汇编语言源代码。我的主表是由操作码驱动的,它有关于每个操作码的信息,包括寄存器操作数的数量/用法、操作的大小等。它当前存储为dict,操作码作为键,指示符列表作为值。它的工作,但它很容易搞砸,我不会记得它是如何工作时,我必须修复它。有没有更好的方法把数据和处理分开?你知道吗

opdefs={ #operator defs
    #[number of register operands,
    # <for each operand code 1=dest,2=src,3=both,4=overhead>,
    #storage use code:0 for none, 1 for dest, 2 for source
    #operation size(-means call opsizer routine)]
    'cpy2': [2,1,2,0,4], 'cpy1': [2,1,2,0,2], 'cpy4': [2,11,12,0,8],

其中,cpy2有两个寄存器操作数,第一个是目标,第二个是源,没有存储引用,长度为4字节。你知道吗

在标记文件的每一行之后,主循环

numoperands=opdefs[tokens[0]][0] #numer of operands
for operandnum in range(1,numoperands+1):
    if opdefs[tokens[0]][operandnum]==1: #dest register
        destreg(tokens[operandnum]) #count times register is loaded

我不介意我只运行一次,但我认为必须有一个更好的方式来组织或编码这个。有什么建议吗?你知道吗


Tags: ofregisterfor源代码code寄存器dest汇编语言
1条回答
网友
1楼 · 发布于 2024-05-29 04:45:28

首先,使用^{} class factory创建一个类似元组的对象来替换列表;将运算符代码存储在该对象中的元组中:

from collections import namedtuple
opdef = namedtuple(opdef, 'opcount opcodes storage size')

opdefs = {
    'cpy2': opdef(2, (1, 2), 0, 4),
    'cpy1': opdef(2, (1, 2), 0, 2),
    'cpy4': opdef(2, (11, 12), 0, 8),
}

现在您可以用opdefs[token[0]].opcountopdefs[token[0]].size等来解决这些问题,这样就更容易阅读了。如果您觉得更容易阅读,可以使用这些名称来定义条目:

opdefs = {
    'cpy2': opdef(opcount=2, opcodes=(1, 2), storage=0, size=4),
    # ...
}

您可以省略opcount参数,而只使用len(opdefs[token[0]].opcodes)。你知道吗

接下来,您可以使用常量来表示您拥有的各种选项。对于storage,您可以使用:

S_NONE, S_DEST, S_SOURCE = range(3)

例如,然后通篇使用这些名称:

opdefs = {
    'cpy2': opdef(opcount=2, opcodes=(1, 2), storage=S_NONE, size=4),
    # ...
}

因为我们对操作码使用一个单独的元组,所以您只需在这些元组上循环:

operands=opdefs[tokens[0]].opcodes
for operandnum, opcode in enumerate(operands, 1):
    if opcode == 1: #dest register
        destreg(tokens[operandnum]) #count times register is loaded

相关问题 更多 >

    热门问题