They wanted the code to be sequential operations so the branch predictor wouldn't be influenced. If they used
if
or the ternary conditional operation, it would be compiled into jumps, which influence the branch predictor.
Now let's see how it works.
> (j % 6)
This gives j modulo 6, the result will be 0 if j can be divided by 6 and between 1 and 5 otherwise.
>((j % 6) -1)
This subtracts one from the modulo. If j can be divided by 6 the result will be -1, which is
0xFFFFFFFF
in hexadecimal (computers use two-complement to represent numbers). Otherwise it will be between 0x00 and 0x04.
>((j % 6) -1) & ~0xFFFF
Here
~0xFFFF
means negating 0x0000FFFF which means flipping the bits so it becomes 0xFFFF0000. The bit-wise and (
&
) of this and the result of the previous expression will be 0xFFFF0000 if it was -1 (divisible by 6) and 0x00000000 otherwise.
Which is what they wanted, but without the jumps. There are no "if this, then that", just a sequence of mathematical operations, so the branch predictor, which is only concerned with conditional execution won't be involved. It's a bit cryptic at first but if you know all the operations it is actually pretty straightforward.
I used 32 bit long words in this post, for 64 bit processors just double the length of the values.