对于负整数,返回零 [英] Return zero for negative integers

查看:95
本文介绍了对于负整数,返回零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个朋友只是抛出了一些类似于以下C#代码的代码:

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.

顺便说一句,我知道Math.Max(0, i);

推荐答案

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)

(来源:此列表按位技巧).

如果分支机构在您的平台上非常昂贵,那么我认为在某些内部循环中可能是值得的,但这是相当模糊的,不是我想在外部遇到的那种事情时间敏感功能.

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.

这篇关于对于负整数,返回零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆