문제

Trying to understand some assembly language, but I am not sure if I am understanding it correctly

movl 8(%ebp),%eax // assign %eax to a variable, say var
testl %eax,%eax // test if var is > 0 or not. if var is > 0, jump to .L3
jge .L3
addl $15,%eax // add 15 to var
.L3:
sarl $4,%eax // shift var 4 to the right , which is the same as multiplying var by 16

given by above understanding, I wrote the following code

int function(int x){    
    int var = x;    
    if(var>0) {
        ret = ret * 16;
    }    
    ret = ret + 15;    
    return ret;        
}

however, my assembly code looks like the following

movl 8(%ebp), %ebp
movl %eax. %edx
sall $4, %edx
test1 %eax, %eax
cmovg %edx, %eax
addl $15, %eax

am I misunderstanding the original assembly code somewhere?

Edit: is there perhaps a loop involved?

올바른 솔루션이 없습니다

다른 팁

Notice that the code continues with the shift even after the addition, and that jge also includes the equal case. Thus the code could look more like this:

int function(int x) {
    int ret = x;
    if (ret >= 0) goto skip_add;
    ret = ret + 15;
skip_add:
    ret = ret / 16;
    return ret;
}

Or, to avoid the goto, reverse the condition:

int function(int x) {
    int ret = x;
    if(ret < 0) {
        ret = ret + 15;
    }
    ret = ret / 16;
    return ret;
}

PS: shifting right is division, shifting left would be multiplication.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top