Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the div instruction to find remainder in x86 assembly?

mov eax, 0
mov ebx, 0
mov edx, 0
mov ax, 31
mul cx
mov bx, 12
div bx
add bp, ax
mov eax, 0
mov ebx, 0
mov bp, bp
mov al, 7
div al

can anyone tell me whats wrong with the div al instruction in this block of code, so as I'm debugging every number of bp i calculated, when i divide by al it give me 1 as the remainder, why is this happen?

the remainder should be store back to ah register

thank in advance

edited code :

mov eax, 0
mov ebx, 0
mov edx, 0
mov ax, 31
mul cx
mov bx, 12
div bx
add bp, ax
mov eax, 0
mov ebx, 0
mov ax, bp
mov bl, 7
div bl
mov al, 0
like image 508
bluebk Avatar asked May 06 '13 17:05

bluebk


Video Answer


2 Answers

You can't use al as divisor, because the command div assumes ax to be the dividend.

This is an example for dividing bp by 7

mov ax,bp // ax is the dividend
mov bl,7  // prepare divisor
div bl    // divide ax by bl

This is 8 bit division, so yes the remainder will be stored in ah. The result is in al.

To clarify: If you write to al you partially overwrite ax!

|31..16|15-8|7-0|
        |AH.|AL.|
        |AX.....|
|EAX............|
like image 147
typ1232 Avatar answered Sep 26 '22 22:09

typ1232


edited code:

mov eax, 0
mov ebx, 0
mov ax, 31
mul cx
mov bx, 12
div bx
add bp, ax
mov eax, 0
mov ebx, 0
mov edx, 0
mov ax, bp
mov bx, 7
div bx
mov esi, edx 
mov eax, 0
like image 39
bluebk Avatar answered Sep 26 '22 22:09

bluebk