Software 8 Bit Rotations

While working on some graphics code for the 65816 processor, I realized that I needed an 8-bit rotation of a binary value. However, neither the 6502 nor 65816 provide such a rotation — the best you can get is 9-bit (or 17-bit if you're in 16-bit register mode).

The code snips below ought to work both for the 6502 and the 65816, and can be written to even be m/x-bit independent as well.

8/16-bit Rotate Left

Here's a dirty little trick for performing a fairly rapid 8/16-bit rotate-left operation.

asl
adc #0

The idea here is that the ASL instruction will shift bit 7 (or 15) into the carry flag, and a 0 into bit 0. Since the addition can only add one or zero (depending on the state of the carry flag), the result is that bit 0 becomes the former value of the carry bit.

8/16-bit Rotate Right

This is the fastest I could come up with.

lsr
bcc *+2   ; or *+3 for 16-bit mode
ora #$80  ; or #$8000 for 16-bit mode
page_revision: 0, last_edited: 1200779235|%e %b %Y, %H:%M %Z (%O ago)
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License