!pr1
Turning Bit-Masks into Indices.............Bob Sander-Cederlof

A few months ago I presented several ways to turn an index (0-7) into a bit mask (01, 02, 04,...,80).  We got a lot of feedback, including some faster and better programs.  Bruce Love suggested the possibility of the reverse transformation.

According to Bruce, who is a high school teacher in New Zealand, the method which uses the fewest bytes is the one I show in lines 1390-1450.  In order to be fair in comparing different algorithms, I am going to count the RTS opcodes both for bytes and for cycles.  With this in mind, Bruce's routine takes 8 bytes and from 16 to 65 cycles.  This is certainly the smallest way, and it really is pretty fast.

Bruce mentioned that he had written several other programs to solve the same problem:  one used the X-register, took 26 bytes with an average of 33.5 cycles;  another without useing X or Y took 28 bytes and an average of 39 cycles.  Unfortunately, he did not include a copy of either of these.

I worked out four more methods, shown in the listing after Bruce's.  I wrote a test driver which is in lines 1000-1310.  The test driver calls each routine, printing the results of each, for all possible values of the bit-mask.

The following table summarizes the data for the five algorithms:

                               # of cycles
                       bytes  min  max  ave
     SMALLEST.WAY         8    16   65  40.5
     WAY.WITH.X          26    25   42  33.5
     WAY.WITHOUT.X       23    14   30  22
     ANOTHER.WAY.W...    32    14   24  18.375
     STRAIGHT.TEST...    33    14   27  18.5

If the SMALLEST.WAY is not fast enough, I would probably go with the one named WAY.WITHOUT.X.  It is almost as fast as the fastest, and is the shortest of the longer routines.  Of course, some of you may come up with better and faster ones....
