0

I tried using the following codes to get the quotient and reminder 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

reminder 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 reminder in a reserved space
mov dword [reminder], edx

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

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

; Exit the program
xor eax, eax
ret

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

Daniel
  • 1
  • 1
  • 1
    It's an exact duplicate of [nasm idiv a negative value](https://stackoverflow.com/q/9072922); I edited the duplicate list after the initial closure, but before your last edit. If you're printing the result properly, `cqo` works to sign-extend RAX into RDX:RAX before `idiv`. It's weird that you're doing slow 64-bit division but only using the low 32 bits of the quotient and remainder, but should work for small values. (Truncating the bit-pattern like you're doing is the correct way to do a narrowing integer conversion in 2's complement.) – Peter Cordes Jun 04 '23 at 06:17
  • Also, you could use one format string with two conversions and only call `printf` once, making your program simpler. – Peter Cordes Jun 04 '23 at 06:21
  • 1
    Also, your comment on `xor rdx, rdx ; Clear RDX to zero for the remainder` doesn't make sense. You're not zeroing it because that's where the remainder will go, you're zeroing it as an input to IDIV, the high half of the quotient. (But of course zero-extension isn't the right thing to do for signed inputs.) The linked duplicates also explain that. – Peter Cordes Jun 04 '23 at 06:24

0 Answers0