Code: Select all
LDA #0
LDX #16
.loop
ASL zp
ROL zp+1
ROL A
CMP #xx
BCC skip
SBC #xx
INC zp
.skip
DEX
BNE loop
Of course, for divisors that are powers of 2, shifting/masking is shorter and faster.
Moderator: Moderators
Code: Select all
LDA #0
LDX #16
.loop
ASL zp
ROL zp+1
ROL A
CMP #xx
BCC skip
SBC #xx
INC zp
.skip
DEX
BNE loop
The routine has a serious flaw. It does not handle most significant bit of the dividend at all.Mike wrote:[..]zp and zp+1 contain the 16-bit value to be divided, and the result afterwards. The 8-bit divisor constant is encoded in the immediate fields of CMP #xx and SBC #xx. The remainder ends up in the Accumulator.Code: Select all
LDA #0 LDX #16 .loop ASL zp ROL zp+1 ROL A CMP #xx BCC skip SBC #xx INC zp .skip DEX BNE loop
[..]
Code: Select all
LDA #0
LDX #16
.loop
ASL zp
ROL zp+1
ROL A
BCS subtract ; added: always greater if overflow into bit 9
CMP #xx
BCC skip
.subtract
SBC #xx
INC zp
.skip
DEX
BNE loop
Code: Select all
LDA zp+1
CMP #xx ; optional: check if dividend is to great
BCS overflow ; for a 8 bit quotient
ASL zp
LDX #8
.loop
ROL A
BCS subtract ; added: always greater if overflow into bit 9
CMP #xx
BCC skip
.subtract
SBC #xx
SEC ; always, because bit 9 overflow may turn the carry
.skip
ROL zp
DEX
BNE loop
The first restriction is correct, the second one is not. The routine in the OP works fine for all dividends $0000..$FFFF, provided the divisor is less than $80, and regardless whether the high byte of the dividend is greater than or equal to the divisor, as the routine returns the full 16 bit result.This routine is only save for divisors less than $80 and dividends less than $8000 [...]
Not quite. It really depends on the (expected) size of the quotient. With one of the use cases I intended (divisor = 10 to extract decimal digits), a non-0 high byte in the result is very likely, and so this routine needs to loop over all 16 quotient bits.If the divisor has only 8 bit then 8 or 9 iterations are really needed [...]