Reputation: 13195
I have the following calculation:
unsigned int a;
unsigned b = (a < 4) ? a : 4;
Is it possible to convert the second line to a branch free format?
Thanks!
Upvotes: 2
Views: 109
Reputation: 26105
You could use a conditionally applied mask:
unsigned int a, b, t, m;
t = a - 4;
m = 0 - ((int)t < 0); // mask of all 0s or all 1s
b = (t & m) + 4; // mask all 1s: b=a-4+4; mask all 0s: b=4
Upvotes: 1
Reputation: 811
Try this:
b = (a >= 4) * 4 + (a < 4) * ((a >> 1) & 1) * 2 + (a < 4) * (a & 1);
Explanation: we are returning 4 by "zeroing" the 2 least significant bits if a >= 4. If a < 4, we use these 2 least significant bits.
Upvotes: 2