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开发者_Python百科 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.
How about:
int i = ...;
return i & ~(i >> 31);
The below will do the trick and the code reads so well it practically don't need a comment ;)
((((0x80000000 & i) >> 31)^1) * 0xFFFFFFFF) & i
then again
int temp = (0x80000000 & i); //get the most significant bit (1 for negative 0 for positive)
temp = (temp>>31)^1; //more it to the least significant and not it (we now have 0 for negative numbers and one for positive)
temp *= 0xFFFFFFFF; //get a lof of F's if it's positive or a lot of zeros if the number was negative
temp = temp & i; //and the F's/zeros with the original number
and voila zero for all negative number and all positive are left unchanged
Short answer: No.
Bit operators do something very different, or rather are used for different problems.
If you know the size of your integers, you could test the highest (most significant) bit; if it's 1, the number is negative and you can act on that. But that would be a heck of a lot more work than the simple "<" test.
Not bitwise but different:
return (i + Math.abs(i))/2
EDIT:
return (int)(i/2f + Math.abs(i)/2f)
精彩评论