This question is related to Array of pairs of 3 bit elements
This array has 52 pairs (about 40 bytes), and I want to find the first pair before the specified one that has it’s values different from 0 (used pair).
The obvious solution would be to check each pair < than this one (scan from right to left), but this seems to be very inefficient if there are many unused pairs (set to 0).
This image may explain better the situation:

Pairs 0, 1 and 51 are used.
I want to find the first used pair before 51 (which is 1 here).
I tried tricks like
if(*((int *)&array[arrayPos]) == 0) {
arrayPos -= sizeof(int);
pairPos -= ???
}
The problem here is that subtracting from pairPos is not that simple, because of the 6 bits/pair, so I ended with a lookup table based on some relations between pairPos and arrayPos, and all this made the solution perform like the trivial one.
Is there any way to make this lookup faster ? Another problem is that there is only 1 unused byte… maybe I can make space for another 4. If there were at least 7 I could use a bitmap of the array and it would be much faster to skip over unused pairs.
The best solution I found was:
1. make the items 1 byte (not 6 bits than before) – thanks Skizz
2. use a bitmap to see which item is the nearest on the left. This was much faster than going back with the technique described by djna.
The speed improvements are impressive:
in one test case, from 13s it’s now 6.5s
in another one, from 7.4s to 3.6s
The performance has doubled 😀
Thanks again for your answers!