简体   繁体   中英

NASM Assembly mathematical logic

I have a program in assembly for the Linux terminal that's supposed to work through a series of mathematical manipulations, compare the final value to 20, and then using if logic, report <, > or = relationship. Code is:

segment .data

out_less     db "Z is less than 20.", 10, 0
out_greater  db "Z is greater than 20.", 10, 0
out_equal    db "Z is equal to 20.", 10, 0

segment .bss

segment .text

global main
extern printf

main:

    mov    eax, 10
    mov    ebx, 12
    mov    ecx, eax
    add    ecx, ebx    ;set c (ecx reserved)

    mov    eax, 3
    mov    ebx, ecx
    sub    ebx, eax    ;set f (ebx reserved)

    mov    eax, 12
    mul    ecx
    add    ecx, 10     ;(a+b*c) (ecx reserved)

    mov    eax, 6
    mul    ebx
    mov    eax, 3
    sub    eax, ebx
    mov    ebx, eax    ;(d-e*f) (ebx reserved) reassign to ebx to free eax

    mov    eax, ecx
    div    ebx
    add    ecx, 1      ;(a+b*c)/(d-e*f) + 1

    cmp    ecx, 20
    jl     less
    jg     greater
    je     equal

    mov    eax, 0
    ret

less:

    push    out_less
    call    printf
    jmp     end

greater:

    push    out_greater
    call    printf
    jmp     end

equal:

    push    out_equal
    call    printf
    jmp     end

end:

    mov     eax, 0
    ret

Commands for compiling in terminal using nasm and gcc:

nasm -f elf iftest.asm
gcc -o iftest iftest.o
./iftest

Equivalent C code would be:

main() {
    int a, b, c, d, e, f, z;
    a = 10;
    b = 12;
    c = a + b;
    d = 3;
    e = 6;
    f = c - d;
    z = ((a + b*c) / (d - e*f)) + 1;

    if (z < 20) {
        printf("Z (%d) is less than 20.\n", z);
    }
    else if (z > 20) {
        printf("Z is greater than 20.\n");
    }
    else {
        printf("Z is equal to 20.\n");
    }
}    

The current output is incorrect. The C code will report that z = -1, and therefore less than 20, but the assembly code outputs Z is greater than 20. I've tried printing out the final value, but I run into this issue where printing the value somehow changes it. I've checked and rechecked the math logic and I can't see why it shouldn't give the correct value, unless I'm using the math operators incorrectly. Any and all help is appreciated.

I think the problem is here:

div    ebx
add    ecx, 1      ;(a+b*c)/(d-e*f) + 1

The result of the div instruction is not in ecx .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM