<分区>
int x1 =-2 ;//any value
if(x1 < 0)
x1 = 0;
我正在尝试使用按位运算符
int result = !(x1 >> 31) & (((~x1 + 1) >> 31) & 1);
x1 = result !=0 ? x1:result;
我不想使用条件运算符来探索二元运算符的更多用法。这背后没有任何其他意图。如果有任何方法,请告诉我。 有什么办法吗??
标签 c
<分区>
int x1 =-2 ;//any value
if(x1 < 0)
x1 = 0;
我正在尝试使用按位运算符
int result = !(x1 >> 31) & (((~x1 + 1) >> 31) & 1);
x1 = result !=0 ? x1:result;
我不想使用条件运算符来探索二元运算符的更多用法。这背后没有任何其他意图。如果有任何方法,请告诉我。 有什么办法吗??
最佳答案
假设 32 位整数和二进制补码,以下是否可以?
unsigned int x = (unsigned int)-2;
x &= (x >> 31) - 1;
我使用unsigned
因为根据标准
The result of
E1 >> E2
isE1
right-shiftedE2
bit positions. .... IfE1
has a signed type and a negative value, the resulting value is implementation-defined.
关于条件检查替换为按位运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29756368/