首页 > 解决方案 > 没有 div 的 ASM 8086 除法

问题描述

我需要在 asm 8086 中编写一个类似 b=a/6 但没有 DIV 指令的程序。我知道如何使用 SAR,但只有 2、4、8、16 ......

mov ax,a
sar ax,1 ;//div a by 2
mov b,ax

我的问题是我怎样才能做到 div by 6?

标签: assemblyintelx86-16emu8086integer-division

解决方案


给出另一个答案的方法是简单的蛮力循环,对于较大的值可能需要一段时间a。这是一个使用较大块的版本(像长除法问题一样工作),专门编码为将有符号数除以 6:

; signed divide by 6
    mov ax,a
    mov cx,1000h  ; initial count of how many divisors into ax to check for
    mov bx,6000h  ; value of "divisor * cx"
    xor dx,dx     ; result
top:
    cmp ax,bx
    jl skip
    ; we can fit "cx" copies of the divisor into ax, so tally them
    add dx,cx
    sub ax,bx
    ; optionally can have a "jz done" here to break out of the loop
skip:
    shr bx,1
    shr cx,1
    jnz top

    ; copy result into ax
    mov ax,dx

如果需要除 6 以外的东西,则需要调整初始值cx和值。是保留第 14 位设置的除数的 2 的幂(因为第 15 位是符号位;对于无符号除法,您希望设置第 15 位)。是 2 的幂。如果初始值有限制,您可以调整初始值和值,但必须小心,因为如果将它们设置得太小,您会得到错误的答案。bxcxbxacxbx


推荐阅读