Return zero for negative integers

∥☆過路亽.° 提交于 2019-12-08 16:37:38

问题


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


回答1:


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.




回答2:


How about:

int i = ...;

return i & ~(i >> 31);




回答3:


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




回答4:


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.




回答5:


Not bitwise but different:

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

EDIT:

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


来源:https://stackoverflow.com/questions/1683029/return-zero-for-negative-integers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!