[Return to Main Page]

Efficient nybble-swap on 6502 by Garth Wilson
[Up to Source Code Repository]


David Galloway made this suggestion on the facebook 6502 Programming group, for swapping nybbles. $36 becomes $63, $A1 becomes $1A, etc.. It takes only 8 bytes and 12 clock cycles, and no variables, no stack usage, no look-up table, no X or Y usage. It uses only the accumulator and status register.

        ASL  A
        ADC  #$80
        ROL  A
        ASL  A
        ADC  #$80
        ROL  A

Straight-lining it takes only five bytes more than a subroutine call and cuts the execution time in half. It could of course be put in a macro. How that is done exactly will depend on your assembler, but might go something like:

SWN:    MACRO
        ASL  A
        ADC  #$80
        ROL  A
        ASL  A
        ADC  #$80
        ROL  A
        ENDM
 ;-------------

and would be called simply with SWN as if it were an assembly-language mnemonic. You probably won't use it many times in a program anyway for the straight-lining to take up appreciable memory, but you might want it pretty fast when you do.

Last page update: Oct 27, 2017.