Return zero for negative integers

A friend simply spells out code similar to the following C # code:

int i = ...; return i < 0 ? 0 : i; 

It made me think. Is there any β€œother” way to return zero for negative integers or the current positive value? More specifically, I am looking for bitwise operations, if possible.

By the way, I know Math.Max(0, i);

+7
c # bit-manipulation
source share
5 answers

What happened to Math.Max ?

You can make an equivalent without a branch using bitwise operations:

 r = x ^ ((x ^ y) & -(x < y)); // == max(x, y) 

If you replace zero, it will fall on:

 r = (y & -(0 < y)); // == max(0, y) 

(Source: this list of bitwise tricks.)

If the branches were extremely expensive on your platform, it might have cost in some kind of inner loop, but it is rather obscure, and not something that I would like to meet outside of an extremely time-sensitive function.

+25
source share

What about:

int i = ...;

return i and ~ (i β†’ 31);

+4
source share

Below is the trick, and the code reads so well that it hardly needs 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 if it 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 numbers, and all positive numbers remain unchanged

+4
source share

Short answer: None.

Bit operators do something completely different or, rather, are used for different tasks.

If you know the size of your integers, you can check the highest (most significant) bit; if it is 1, the number is negative, and you can act on this. But that would be much more than just a "<" test.

+3
source share

Not bitwise, but another:

 return (i + Math.abs(i))/2 

EDIT:

 return (int)(i/2f + Math.abs(i)/2f) 
+3
source share

All Articles