条件检查替换为按位运算符

标签 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 is E1 right-shifted E2 bit positions. .... If E1 has a signed type and a negative value, the resulting value is implementation-defined.

关于条件检查替换为按位运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29756368/

相关文章:

c - C中的函数指针问题

C:TCP发送内存页

使用不同的堆栈指针调用 C 函数 (gcc)

c - 如何从字符串中读取以空格分隔的整数

c - C 中数组的随机性 数组中的随机性

c - C程序中的输入

c - 文件写入/读取速度有多快

c++ - 错误 : ‘IOV_MAX’ undeclared (first use in this function)

c - 很难在我的 C 程序中调试我的链表

c - 当 pthread 退出函数时会发生什么