Mr *_*osh 3 c expression bitwise-operators
https://www.geeksforgeeks.org/compute-the-minimum-or-maximum-max-of-two-integers-without-branching/
我试图找到寻找两个整数之间的最大值和最小值的替代方法,并遇到了以下用于该操作的代码。任何人都可以澄清代码中按位运算符的工作和作用:
/*Function to find minimum of x and y*/
int min(int x, int y)
{
return y ^ ((x ^ y) & -(x < y));
}
/*Function to find maximum of x and y*/
int max(int x, int y)
{
return x ^ ((x ^ y) & -(x < y));
}
Run Code Online (Sandbox Code Playgroud)
return y ^ ((x ^ y) & -(x < y));
Run Code Online (Sandbox Code Playgroud)
-(x < y)如果 则为 0,如果x >= y则为 -1(即设置了所有位的 int)x < y。请注意foo & -1 == foo和foo & 0 == 0对于所有foo. 因此,如果x < y,我们得到y ^ x ^ y,它等于x因为y ^ y抵消了。否则我们得到y ^ 0,即y。所以我们得到xifx < y和yelse,这正是您想要从名为 的函数中得到的min。
因为max它是同一件事,除了我们返回yifx < y和xelse 。