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:
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?
- None Found
- My recommended books