My college gave me a exercise:
1. Create a new document in Jasmin
2. Use the AL-Register to to add 9 to 8.
3. Subtract 2.
There's a DIV
instruction which does division, but you'll need to put the dividend into AX
(or one of its siblings) first.
The div and idiv
instructions don't have forms that take an immediate. They only take one explicit operand (register or memory), with the dividend being implicit in AX, or DX:AX, EDX:EAX, or RDX:RAX.
See this answer for how to use them.
But x86 in 16 and 32-bit mode does have an immediate-division instruction, and it's actually slightly faster than div r/m8
on Intel CPUs before Skylake: aam 7 will divide AL by an immediate 7, placing the quotient in AH, remainder in AL. (https://agner.org/optimize/ says that on Haswell it has 1 cycle lower latency, and 1 cycle better throughput than div r8
. And it's 8 uops instead of 9.)
Note that it's different from mov cl, 7
/ div cl
, which takes the whole of AX as the dividend, and places quotient in AL, remainder in AH.
AAM is not available in 64-bit long mode, removed along with the other less-useful legacy BCD instructions. But if it saves uops overall (including mov
an immediate to a register), it could be useful. On Skylake, it costs 11 uops vs. 10 for div r8
, and has 1c worse throughput, and same latency.
div
operation divides (unsigned) the value in the AX, DX:AX, or EDX:EAX registers (dividend) by the source operand (divisor) and stores the result in the AX (AH:AL), DX:AX, or EDX:EAX registers.
source
so, to divide value in al, you need to do:
mov ah, 0 # clean up ah, also you can do it before, like move ax, 9
mov bl, 7 # prepare divisor
div bl # al = ax / bl, ah = ax % bl
after that al will contain quotient and ah will contain remainder
This code works for only single digit numbers division.
.model small
.data
msg1 db 'enter dividend:$'
msg2 db 10,13,'enter divisor:$'
result db 10,13,'result is:$'
dividend db ?
divisor db ?
.code
.startup
mov ax,@data
mov ds,ax
mov ah,9
lea dx,msg1
int 21h
mov ah,1
int 21h
sub al,30h
mov dividend ,al
mov ah,9
lea dx,msg2
int 21h
mov ah,1
int 21h
sub al,30h
mov divisor , al
mov al,dividend
mov bl,divisor
mov ah,0
div bl
mov ah,9
lea dx,result
int 21h
mov ah,2
add al,30h
mov dl,al
int 21h
mov ah,4ch
int 21h
end