Skip to content

Instantly share code, notes, and snippets.

@magical
Created May 31, 2012 01:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save magical/2840359 to your computer and use it in GitHub Desktop.
Save magical/2840359 to your computer and use it in GitHub Desktop.
multiplication and division in x86 asm
global Mul
global Div
; input: [esp+4] m
; [esp+8] n
; return: eax low word of product
; edx high word of product
Mul:
push esi
push edi
; ecx n
mov ecx,[esp+12]
; esi,edi m
mov edi,[esp+16]
xor esi,esi
; edx,eax p
xor eax,eax
xor edx,edx
and ecx,ecx
jz .done
.loop:
shr ecx,1
jnc .zerobit
add eax,edi
adc edx,esi
.zerobit:
shl edi,1
rcl esi,1
and ecx,ecx
jnz .loop
.done:
pop edi
pop esi
ret
; quotient in eax
; remainder in edx
Div:
push ebx
push esi
xor eax,eax ; q
mov ebx,[esp+16] ; d
xor edx,edx ; r
mov esi,[esp+12] ; n
mov ecx,32 ; i
.loop:
shl eax,1
shl edx,1
shl esi,1
adc edx,0
cmp edx, ebx
jl .ge
sub edx, ebx
add eax,1
.ge:
dec ecx
jnz .loop
.done:
pop esi
pop ebx
ret
; vim:ft=nasm
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment