0

I have to finish a college assignment and I'm having issues with one particular assertion on an unit test. Essentially the exercise is to check if number A is multiple of number B in Assembly x86 (1 if yes, 0 if no). I have every test passing with the exception of one where both numbers are negative.

What I have in Assembly is:

    pushq %rbp
    movq %rsp, %rbp
    pushq %rbx

    movl A(%rip), %eax
    js isDividendLessThanZero
    movl B(%rip), %ecx
    js isDivisorLessThanZero
    cmpl $0, %ecx  
    je isZero

    xor %edx, %edx 
    idivl %ecx 

    cmpl $0, %edx 
    jne isZero

    movl $1, %eax
    jmp end

    isZero:
    movl $0, %eax

    isDivisorLessThanZero:
    neg %ecx

    isDividendLessThanZero:
    neg %eax

    end:

    popq %rbx
    movq %rbp, %rsp
    popq %rbp
    ```

I have added the 2 last conditional blocks to negate the divisor and/or the dividend if they/re negative, but it's not having any effect. Could you please tell me what I'm doing wrong? Thanks!
lenric
  • 25
  • 6
  • 2
    The `mov` instruction does not set flags. Add a `test` instruction to set flags. – fuz Oct 19 '22 at 23:38
  • 1
    `xor %edx, %edx` zero-extends EAX, but your input is signed so you should be sign-extending with `cdq` before `idiv`. See [When and why do we sign extend and use cdq with mul/div?](https://stackoverflow.com/q/36464879) / [Why should EDX be 0 before using the DIV instruction?](https://stackoverflow.com/q/38416593). Checking for `edx==0` after that is correct to detect an exact multiple. You don't need to take the absolute value before signed division if you do it properly; `-10 / 5` is `-2` with remainder `0` for example. – Peter Cordes Oct 20 '22 at 00:07
  • @PeterCordes thanks a lot, that worked! I could delete the 2 ifs to check if the dividend and divisor are negative. Thanks a lot! :) – lenric Oct 20 '22 at 00:21

0 Answers0