Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/272.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为负整数返回零_C#_Bit Manipulation - Fatal编程技术网

C# 为负整数返回零

C# 为负整数返回零,c#,bit-manipulation,C#,Bit Manipulation,朋友只需抛出一些类似于以下C#代码的代码: inti=。。。; 返回i

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

inti=。。。;
返回i<0?0:i;
这让我思考。对于负整数或当前正值,有没有“不同”的方法返回零?更具体地说,如果可能的话,我正在寻找逐位操作

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

简短回答:否

位运算符做的事情非常不同,或者更确切地说是用于不同的问题


如果知道整数的大小,可以测试最高(最高有效)位;如果它是1,那么这个数字是负数,你可以根据这个数字采取行动。但这比简单的“Math.Max有什么问题?”

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

r = x ^ ((x ^ y) & -(x < y)); // == max(x, y)
r=x^((x^y)和-(x
如果替换为零,它将折叠为:

r = (y & -(0 < y)); // == max(0, y)
r=(y&-(0
(来源:按位技巧。)


如果分支在您的平台上非常昂贵,我想这在某些内部循环中可能是值得的,但它非常模糊,并且不是我希望在非常时间敏感的函数之外遇到的那种情况。

不是按位而是不同的:

return (i + Math.abs(i))/2
编辑:

那么:

int i=


返回i&~(i>>31);

下面的代码就可以了,代码读起来非常好,几乎不需要注释;)

然后再次

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

瞧,所有的负数和正数都保持不变,等于零

这算什么代码高尔夫?我告诉你的朋友不要扔代码。这可能会打中别人的眼睛。+1我再也不会扔代码了!!如果编译器已经做了这个优化,我也不会感到惊讶。通常(xreturn (int)(i/2f + Math.abs(i)/2f)
((((0x80000000 & i) >> 31)^1) * 0xFFFFFFFF) & i
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