« Alternating without a branch | Main | Add so as to multiply »

Alternating three ways without branching

Suppose you want a variable to cycle between three different values in a loop, like this.
threebranch.jpg
If this code is executed in a loop, then x will alternate between the values a, b, and c repeatedly. But how may we achieve the same effect without any branching? Tricky...here's a little scheme I've cooked up to do just that. It cheats by using two variables x and y. The mysterious "plus-in-a-circle" operation is bitwise exclusive-or (exor).

First, before the loop starts, initialize x and y, and precompute the magic constant s as follows.
precomp.jpg
Then inside the loop execute the following non-branching code.
update.jpg
Note that x cycles between the following three values, because of the self-inverse property of exor (see Alternating without a branch).
threevals.jpg
So if we exor x with the magic constant s we get a value that cycles between a, b, and c, because of the self-inverse property of exor, once again.

There's a secret connection between this scheme and the Fibonacci numbers...

Comments

I like this very much. It reminds me that it is easy to forget the mathematical foundations of the code we write. I write code for limited memory embedded processors as a hobby and this seems like it would be a very useful alternative to a branch instruction sequence.

I also just attended a lecture on Nvidia's CUDA architecture and this seems like a good optimization technique for certain operations. The architecture performs best when many threads are performing exactly the same operation, and this might help avoid the problem of the instruction sequence diverging because of the branch instructions.

Post a comment

(If you haven't left a comment here before, you may need to be approved by the site owner before your comment will appear. Until then, it won't appear on the entry. Thanks for waiting.)

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.