https://www.geeksforgeeks.org/compute-the-minimum-or-maximum-max-of-two-integers-without-branching/
I was trying to find alternative ways of finding maximum and minimum between two integer and came across the following code which is used for the operation.can anyone please clarify the working and role of the bitwise operator in the code:
/*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));
}
return y ^ ((x ^ y) & -(x < y));
-(x < y)
will be 0 if x >= y
and -1 (i.e. an int with all bits set) if x < y
. Note that foo & -1 == foo
and foo & 0 == 0
for all foo
. So if x < y
, we get y ^ x ^ y
, which is equal to x
because y ^ y
cancels out. And otherwise we get y ^ 0
, which is y
. So we get x
if x < y
and y
otherwise, which is exactly what you'd want from a function named min
.
For max
it's the same thing, except we return y
if x < y
and x
otherwise.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With