Some CPU instructions sets offer a way of selecting bits from either of two registers based on the bits of a third register. For example, the SPUs of the CELL in the PS3 have the selb instruction:

selb rt,ra,rb,rc

The result of selb is placed in rt and each bit of rt is either the corresponding bit from ra (if the bit in rc is 0) or from rb (if the bit in rc is 1).

Expressed in a familiar C-style notation, for all bits b in parallel, we are executing the statement:

if (rcb)
rtb = rbb;
else
rtb = rab;

It is hopefully pretty evident that if no selb-like instruction is present, we can still express this selection to perform all if-statements in parallel, without using branches, through the expression:

rt = (rb & rc) | (ra & ~rc);

Not as obvious (at least not at first glance) is the old-school bit trick for implementing the same operation:

rt = ((ra ^ rb) & rc) ^ ra;

Chris Crawford points out that asking what that last line of code does, used to be an interview question at Atari back in 1979 (except, of course, phrased in 6502 assembly language). Would you have been hired?

Similar Posts:

I’ll thankfully hide behind the fact that I wasn’t even born back then, but I wouldn’t have been hired. Bitwise operations don’t seem to get the attention they deserve anymore though. At least when I was taught Java back in the day, I don’t recall hearing a single word on these operators.

Out of cursiosity, why did that last trick get thought up? Is it really the single bit operation less that makes the difference? If so, I don’t know if I regret not being born earlier :)

Rim, in the good ol’ days you would see it in, amongst other things, sprite code on the Apple II. It took some google-fu to find an example of this use, but here’s some 6502 code from Bill Budge et al’s December 1984 BYTE magazine article “Preshift-Table graphics on Your Apple” (from retyped code listing posted to comp.sys.apple2.programmer):

guardian said,

supzi said,

If I can’t use 64 bits ints or 33 bits, in other words there’s no way to know if a subtraction did an overflow then I would consider splitting the 32 bits, check the first bit, then check the remaining bits, something like this :