Wednesday, August 21

Dirty Tricks For 6502 Programming

We know the 6502 isn’t exactly the CPU of choice for today’s high-performance software, but with the little CPU having appeared in so many classic computers — the Apple, the KIM-1, The Commodores, to name a few — we have a real soft spot for it. [Janne] has a post detailing the eight best entries in the Commodore 64 coding competition. The goal was to draw an X on the screen using the smallest program possible. [Janne] got 56 bytes, but two entrants clocked in at 34 bytes.

In addition to the results, [Janne] also exposes the tricks people used to get these tiny programs done. Just looking at the solution in C and then 6502 assembly is instructive. Naturally, one trick is to use the existing ROM code to do tasks such as clearing the screen. But that’s just the starting point.

Some of the efficiencies are good practice on any CPU. For example, converting multiplication in a loop into a running total is always a good idea unless you have hardware multiplication that is as cheap as an addition. Some of the tricks are a bit more specific. For example, it was more efficient to draw the figure at the bottom of the screen and scroll than it was to draw each part at a specific X and Y position.

You might think some of these tricks aren’t really dirty, but then you’ll see self-modifying code. A legitimate hack, but always messy. There are also some special tricks used to get the C64 to load the machine code without going through BASIC first.

You might think 34 bytes would be the smallest possible program. You’d be wrong. After the contest, everyone had a look at all the entries and several people were able to come in even smaller — in one case, 29 bytes.

We wished we could find the PRG files so you could run them on an emulated C64. But we were too lazy to build them up from source. If you don’t have a C64, you could always pull out an FPGA. You can even build a new one — seriously.

No comments:

Post a Comment