c# – 为负整数返回零

栏目: ASP.NET · 发布时间: 7年前

内容简介:翻译自:https://stackoverflow.com/questions/1683029/return-zero-for-negative-integers

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

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

这让我想到了.对于负整数或当前正值,有任何“不同”的方法返回零吗?更具体地说,如果可能的话,我正在寻找按位运算.

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

Math.Max出了什么问题?

您可以使用按位运算在没有分支的情况下执行等效操作:

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

如果替换为零,则会折叠为:

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

(来源: this list 的按位技巧.)

如果你的平台上的分支是非常昂贵的,那么在一些内循环中这可能是值得的,但我认为,这是非常模糊的,而不是我想在极其时间敏感的函数之外遇到的那种东西.

翻译自:https://stackoverflow.com/questions/1683029/return-zero-for-negative-integers


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

An Introduction to Probability Theory and Its Applications

An Introduction to Probability Theory and Its Applications

William Feller / Wiley / 1991-1-1 / USD 120.00

Major changes in this edition include the substitution of probabilistic arguments for combinatorial artifices, and the addition of new sections on branching processes, Markov chains, and the De Moivre......一起来看看 《An Introduction to Probability Theory and Its Applications》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具