TConnolly
Lifetime Supporting Member
Time for another bit hack puzzle.
The following code is how a recycling counter (such as one might use in indexing through an array) is usually done:
I := 1+1
If I > Max_I then I:=0
It is implemented in a for/next or do/while loop. This necessitates a comparison and branching.
However, if for example you want to index a 4 item array, 0 thru 3, then this works really well.
I := (I+1) & 3
This code counts 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2 ....
The general form works for any 2n counts where counting begins at 0 and goes to to 2n-1
I:= (I+1) & (2n-1)
The advantage is that no branching or comparison is involved, as a result it will execute very fast when 2n-1 is a constant.
Now suppose that someone wanted to use some other number. For example, what bit hack will cycle 0 through 5?
The challenge: Pick any integer not equal to (2n-1) and develop a bit hack that can be expressed as a single equation that will count up from 0 to that number and then recyle to 0, or count down from that number to 0 and then reset to that number.
The following code is how a recycling counter (such as one might use in indexing through an array) is usually done:
I := 1+1
If I > Max_I then I:=0
It is implemented in a for/next or do/while loop. This necessitates a comparison and branching.
However, if for example you want to index a 4 item array, 0 thru 3, then this works really well.
I := (I+1) & 3
This code counts 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2 ....
The general form works for any 2n counts where counting begins at 0 and goes to to 2n-1
I:= (I+1) & (2n-1)
The advantage is that no branching or comparison is involved, as a result it will execute very fast when 2n-1 is a constant.
Now suppose that someone wanted to use some other number. For example, what bit hack will cycle 0 through 5?
The challenge: Pick any integer not equal to (2n-1) and develop a bit hack that can be expressed as a single equation that will count up from 0 to that number and then recyle to 0, or count down from that number to 0 and then reset to that number.
Last edited: