Software 8 and 16 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 snippets below ought to work both for the 6502 and the 65816. The first snippet can even be written to 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.

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. The ADC will leave the carry flag clear.

An alternative which has the same speed and size and leaves the original high bit (and thus the low bit of the result) in the carry (which may be more useful than leaving the carry clear in some cases) is: (16-bit version)

cmp #$8000

The 8-bit version is:

cmp #$80

8/16-bit Rotate Right

This is the fastest I could come up with.

bcc *+2   ; or *+3 for 16-bit mode
ora #$80  ; or #$8000 for 16-bit mode
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License