Jump to content
IGNORED

Little 6502 trick


glurk

Recommended Posts

This is actually a question.  Back when I was younger, I used to know a bunch of little 6502 tricks / optimizations, whatever.  And I'm trying to remember one.  Say I have a bit of code like this:

 

LDX MYINDEX
INX
CPX #$03
BNE .noreset
LDX #$00

.noreset    STX MYINDEX

 

So this makes MYINDEX cycle 0,1,2,0,1,2 etc...  But it's so ugly with the CPX and the BNE branch.  Isn't there a more clean / elegant way to do this that takes the same number of cycles each time?  I swear I used to know how to do that.  Or I think I did, LOL.  Using exclusive or, or rotate, or something.  It doesn't even have to use X, it can use the Accumulator instead.  But I just can't figure it out...

Link to comment
Share on other sites

Basically use a cycle of 0-3 instead of 0-2. there's a number of ways to implement it, such as this if you're going to use myindex in X right away:

 

    ldx myindex
    inx
    txa
    and #3
    sta myindex

 

or this if you're going to use myindex later:

 

    inc myindex
    lda myindex
    and #3
    sta myindex

 

Link to comment
Share on other sites

33 minutes ago, Andrew Davie said:

lda index
cmp #2
adc #1
and #3
sta index

 

Perfect.  I thought maybe there was a quicker way than that, but this one is fine.  It's for a 3-frame animation.  If it was 0,1,2,3 it would be easy, but it's not.  I was getting a headache trying to figure this one out, LOL!!  Thanks.

Edited by glurk
Link to comment
Share on other sites

If it's just about an index for an animation, I would do it the other way round: counting down, so you can spare the compare:

   ldx counter
   dex
   bpl @noreset
   ldx #$02
@noreset:
   stx counter

All you need is to reverse the order of the animation frames. But Andrew's a bit faster... of course. But mine's one byte shorter.

  • Like 3
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...
  • Recently Browsing   0 members

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