Daniel
Daniel

Reputation: 11

Why isn't my IDIV instruction working as expected on Windows x64 using NASM assembler?

I tried using the below assembly code to get the quotient and remainder for IDIV instruction, but it didn't work as expected. I use NASM as the assembler.
It prints "The quotient is: -1840700272The remainder is: 1".
I have tried cbq, cbw, etc.. Nothing works.

bits 64

default rel

section .data

    quotientMsg db "The quotient is: %d", 0
    remainderMsg db "The remainder is: %d", 0

section .bss

    remainder resd 1

section .text

    extern printf
    global main
    extern _CRT_INIT

main:

    push    rbp
    mov     rbp, rsp
    sub     rsp, 32
    call    _CRT_INIT

    ; Perform signed division
    mov rax, -15
    mov rcx, 7
    xor rdx, rdx  ; Clear RDX to zero for the remainder
    idiv rcx
    
    ; Store the remainder in a reserved space
    mov dword [remainder], edx

    ; Print the quotient
    mov rcx, quotientMsg
    mov edx, eax
    call printf

    ; Print the remainder
    mov rcx, remainderMsg
    mov edx, dword [remainder]
    call printf

    ; Exit the program
    xor eax, eax
    ret

The expected result should be -2 (quotient) and 1 (remainder).

Upvotes: 0

Views: 134

Answers (0)

Related Questions