5

我有这个 x86 汇编代码,我正在尝试将其转换为 C:

.GLOBAL calculate
calculate:
    pushl %ebp
    movl %esp,%ebp
    movl 12(%ebp),%eax
    movl 8(%ebp),%ecx
    cmpl $2,%ecx
    ja done
    jmp *operations(,%ecx,4)
operation1:
    imull %eax,%eax
    jmp done
operation2:
    negl %eax
    jmp done
operation3:
    addl $0x80,%eax
done:
    leave
    ret
operations:
    .long operation1, operation2, operation3

我的问题是关于这jmp *operations(,%ecs,4)条线的。我认为这是一个 switch 语句,我知道它在内存中是如何工作的,但它如何转换为 C 语言?我不是必须知道这些位置的堆栈上有什么才能为其编写开关吗?

这就是我所拥有的:

int calculate(int a, int b)
{
    if (2 > a)
    {
        return b;
    }
    switch(a) {
        case /* ? */:
            b = (b * b);
            break;
        case /* ? */:
            b = (b * -1);
            break;
        case /* ? */:
            b = (b + 128);
            break;
    }
    return b;
}
4

1 回答 1

0
%ecx == 0 -> operations(,%ecx,4) == operations+0 and operation1 is there  
%ecx == 1 -> operations(,%ecx,4) == operations+4 and operation2 is there  
%ecx == 2 -> operations(,%ecx,4) == operations+8 and operation3 is there

因此,代码应该是

int calculate(int a, int b)
{
    if ((unsigned int)a > 2) /* ja is a comparation instruction for unsigned integers */
    {
        return b;
    }
    switch(a) {
        case 0:
            b = (b * b);
            break;
        case 1:
            b = (b * -1);
            break;
        case 2:
            b = (b + 128);
            break;
    }
    return b;
}
于 2015-09-13T02:24:55.833 回答