A friend just throw some code similar to following C# code:
int i = ...;
return i < 0 ? 0 : i;
That made me think. There's any "different" way to return zero for negative integers, or current positive value? More specifically I'm looking for bitwise operations, if possible.
BTW, I'm aware of Math.Max(0, i);
What's wrong with Math.Max
?
You can do the equivalent without a branch using bitwise operations:
r = x ^ ((x ^ y) & -(x < y)); // == max(x, y)
If you substitute zero, it collapses to:
r = (y & -(0 < y)); // == max(0, y)
(Source: this list of bitwise tricks.)
If branches were extremely expensive on your platform, that might be worthwhile in some inner loop, I suppose, but it's pretty obscure and not the kind of thing I'd like to come across outside of an extremely time-sensitive function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With