Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return zero for negative integers

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);

like image 981
Rubens Farias Avatar asked Nov 05 '09 19:11

Rubens Farias


1 Answers

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.

like image 173
Tim Sylvester Avatar answered Sep 20 '22 04:09

Tim Sylvester