Divide 16-bit value by 8-bit constant
Posted: Wed Jan 03, 2018 6:36 am
During a WIP, I (re-)discovered this handy routine to do an unsigned division of a 16-bit value by an 8-bit constant:
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.
Of course, for divisors that are powers of 2, shifting/masking is shorter and faster.
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.