« favicon.jpg We blog | Main | Alternating three ways without branching »

Alternating without a branch

Suppose you want to achieve the effect of a variable repeatedly alternating between two values
branchswap.jpg
(for example inside a loop) without using a branch. If the variables are just bit patterns such as integers or references (pointers) then you may use bitwise exclusive-or (exor) as follows, and eliminate the branch.
algswap.jpg
Of course, the exor of a and b can be precomputed outside the loop. This relies upon exor being not only commutative and associative, but also acting as its own inverse as follows.
exor.jpg
Informally speaking, exor acts as its own inverse; it is both addition and subtraction in its domain.

Soon (after doing some real work) I will say how to alternate cyclically between three different values in a loop, without branching ... this is a little more amusing.

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.