负数变成0的各种方法

m
microsat
楼主 (北美华人网)
负数变成0 A) int x = -12; if (x<0) { x = 0; }
B) int x = -12; x = max(0, x)
C) int x = -12; 位操作
请高手提供一下用bitwise (位操作)来实现这一功能。 同时,请问,以上三种方法,哪种速度最快? 且还有更快的方法吗?
d
destiny2008
试着回答一下
int x = -12; x = (x >> 31) & x; // 如果x是正数,x >> 31为0,结果是x;如果是负数,x >> 31为-1(即所有位都是1),与x按位与的结果是0
等高手答案
m
mvdk
x = x ^ (~x)
g
gokgs
performance 差别基本 为 0 ,可读性变成最重要, A B 都可以。
f
fengeer
负数变成0 A) int x = -12; if (x<0) { x = 0; }
B) int x = -12; x = max(0, x)
C) int x = -12; 位操作
请高手提供一下用bitwise (位操作)来实现这一功能。 同时,请问,以上三种方法,哪种速度最快? 且还有更快的方法吗?

microsat 发表于 2024-03-20 12:12

int32_t x = -12 x= (~(x >> 31)) & x
Note that here we expect that x>>31 is arithmetic right shift. It is compiler implementation-defined. But for most of compilers, it is true.
But being frankly, I think that bit operation may not be faster than highly optimized C++ code with either A or B, unless you want to do vector operations like SIMD.
w
wenxinhemu
位操作是最快的
g
gokgs
x = x ^ (~x)
mvdk 发表于 2024-03-20 12:16

你异或搞反了吧? 哈哈
x = x^x
纯是脱裤子放屁!