Skip to content

Commit

Permalink
Merge pull request #10 from c128lib/johnpalermo/issue9
Browse files Browse the repository at this point in the history
Add division 16/8 and 16/16.
  • Loading branch information
intoinside authored Jan 25, 2023
2 parents 1574cf2 + 65d51c4 commit 5efe902
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 0 deletions.
2 changes: 2 additions & 0 deletions lib/math-global.asm
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,5 @@
.macro @c128lib_inc16(destination) { inc16(destination) }
.macro @c128lib_dec16(destination) { dec16(destination) }
.macro @c128lib_mulAndAdd(left, right, targetAddr) { mulAndAdd(left, right, targetAddr) }
.macro @c128lib_div16By16(dividend, divisor, remainder) { div16By16(dividend, divisor, remainder) }
.macro @c128lib_div16By8(dividend, divisor, remainder) { div16By8(dividend, divisor, remainder) }
74 changes: 74 additions & 0 deletions lib/math.asm
Original file line number Diff line number Diff line change
Expand Up @@ -191,3 +191,77 @@
dex
bne !-
}

/*
Divides the two-byte number dividend by the two-byte number divisor, leaving the quotient in
dividend and the remainder in remainder. Addressing mode of 16-bit numbers uses little endian.
dividend - 2 bytes (quotient also 2 bytes)
divisor - 2 bytes
remainder - 2 bytes (must be as wide as divisor)
*/
.macro div16By16(dividend, divisor, remainder) {
lda #0
sta remainder // Initialize remainder to 0.
sta remainder+1
ldx #16 // There are 16 bits in the dividend

loop1:
/* Shift the hi bit of dividend into remainder */
asl dividend
rol dividend+1
rol remainder
rol remainder+1

/* Trial subtraction */
lda remainder
sec
sbc divisor
tay
lda remainder+1
sbc divisor+1

/* Check subtraction */
bcc loop2 // Did subtraction succeed?
sta remainder+1 // If yes, save it, else loop2
sty remainder
inc dividend // and record a 1 in the quotient

loop2:
dex
bne loop1

}

/*
Divides the two-byte number dividend by the one-byte number divisor, leaving the quotient in
dividend and the remainder in remainder. Addressing mode of 16-bit numbers uses little endian.
dividend - 2 bytes (quotient also 2 bytes)
divisor - 1 byte
remainder - 1 byte (must be as wide as divisor)
*/
.macro div16By8(dividend, divisor, remainder) {
lda #0
sta remainder // Initialize remainder to 0.
ldx #16 // There are 16 bits in the dividend
loop1:
/* Shift the hi bit of dividend into remainder */
asl dividend
rol dividend+1
rol remainder

/* Trial subtraction */
lda remainder
sec
sbc divisor

/* Check subtraction */
bcc loop2 // Did subtraction succeed?
sta remainder // If yes, save it, else loop2
inc dividend // and record a 1 in the quotient

loop2:
dex
bne loop1

}

0 comments on commit 5efe902

Please sign in to comment.