Skip to content

6502 EOR Tricks: Exclusive-OR Patterns

The EOR (Exclusive OR) instruction offers several valuable optimization techniques for 6502 assembly programming on the Commodore 64. While often overlooked in favor of more intuitive operations, EOR’s bit-toggling behavior enables elegant solutions to common problems.

1. Frame Alternation Technique

This approach enables code execution on every second frame during raster interrupts, useful for distributing workload across frames or creating visual effects at half refresh rate. A zero-page variable alternates between 0 and 1 through repeated EOR operations:

LDA ZPTOGGLE / EOR #$01 / STA ZPTOGGLE / BNE ODDFRAME generates a continuous 0,1,0,1 pattern for selective frame processing.

This technique proves invaluable when CPU budget cannot accommodate all processing within a single frame. By alternating which routines execute, complex effects become achievable without frame rate degradation. The branch can target odd or even frames depending on label placement.

2. Optimized Subtraction via EOR

The standard SEC/SBC sequence consumes 8-9 cycles, but EOR can accomplish subtraction in just 6-7 cycles when working with predictable value ranges. This optimization applies when subtracting from a constant value and the result’s valid range is known.

For instance: LDA BITTABLE,Y / EOR #%00011111 subtracts from that mask value (31) while leaving the carry flag intact as an added benefit. This matters when subsequent code depends on carry state from earlier operations.

The mathematical basis: for values where all bits are potentially set, EOR with a mask effectively computes (mask XOR value), which equals (mask – value) when value contains no bits outside the mask.

3. Optimized Addition via EOR

Adding certain values like #%10000000 (128) requires only 4 cycles with EOR compared to 6 cycles using the CLC/ADC combination, and the carry flag remains unchanged. This specific case toggles the sign bit, useful for signed arithmetic or sprite coordinate manipulation.

When converting between signed and unsigned representations, EOR with $80 provides instant conversion without the overhead of conditional logic or multi-byte arithmetic.

Sprite Animation Applications

EOR proves useful for sprite effects like flickering fire animations or electrical discharge effects. Rather than storing separate sprite variations consuming precious memory, toggling specific bits on alternate frames achieves the same visual result more efficiently. The human eye perceives the rapid alternation as shimmer or glow.

This technique works especially well for multicolor sprites where toggling between two similar colors creates an animated appearance without additional sprite frames. Combined with frame alternation, complex animations emerge from minimal data.

See also: ORA multi-flag condition testing · undocumented opcode techniques · register preservation in IRQs · NMI configuration tutorial