Jump to content
IGNORED

16-bit add less 1


Recommended Posts

I need to add two 16-bit integers (let's call them A and B; A is signed, B isn't) and get the result, less 1. Sure I can do a 16-bit decrement on the result of the addition, but 16-bit DECs require a branch instruction (for MSB roll-over) and I'm trying to save cycles. I considered using a 256 byte look up table of the index value less 1, but this comes unstuck when then LSB is zero, since element 0 is $FF:

 

	ldx a
	lda Less1Tab,x
	clc
	adc b
	sta c
	lda a+1
	adc b+1
	sta c+1
	rts

Less1Tab
	.byte $FF
?Value = $0
	.rept 255
	.byte ?Value
?Value = ?Value+1
	.endr
Making the first element of the LUT $FF seemed like a great idea until I realized it sets the carry flag when subtracting 1 from 0, messing up the MSB. Any more complex and it'll be easier to DEC the result. Any ingenious ideas?
Link to comment
Share on other sites

I don't see why the branch is an issue. This is the first straight optimized way that comes to my mind


clc
lda a
adc b
tax "+2
lda a+1
adc b+1
cpx #0 "+2
beq not_0 "+2/+3
sbc #1 "+2/0, C==1 because X>0
not_0
dex "+2
stx c
sta c+1

 

sums up to 9/10 additional cycles

  • Like 1
Link to comment
Share on other sites

A is signed, B is not (which is just to say B is never >32767). So result may be negative.

Just tested Mapa's modified version of Peter's code and it works nicely, of course. I'll take the three cycle saving, and it looks less clumsy than sticking a DEW after the addition. ;)

Thanks for your help. I thought this quite an interesting little problem. The chosen solution also has the advantage that the second set of coordinates are left pre-loaded in the A and X registers, meaning I can fall straight into the first signed 16 bit clipping comparison without re-loading anything. :)

	.proc Clip
	clc
	lda cx1
	adc Width
	tax
	lda cx1+1
	adc Width+1
	cpx #1
	sbc #0
	sta cx2+1
	dex
	stx cx2
	
	cpx XMin		; is cx2 < XMin?
	sbc XMin+1
	svc
	eor #$80
	bmi NoDraw
	
	clc
	lda cy1
	adc Height
	tax
	lda cy1+1
	adc Height+1
	cpx #1
	sbc #0
	sta cy2+1
	dex
	stx cy2
	
	cpx YMin		; is cy2 < YMin?
	sbc YMin+1
	svc
	eor #$80
	bmi NoDraw

	cmps16 YMax cy1		; is YMax < cy?
	bmi NoDraw
	cmps16 XMax cx1		; is XMax < cx?
NoDraw
	rts
	.endp
Edited by flashjazzcat
  • Like 5
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...