Q:

Compute the minimum (min) or maximum (max) of two integers without branching?

0

Compute the minimum (min) or maximum (max) of two integers without branching?

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Answer:

We can find the minimum (min) or maximum (max) number without the branching with the help of a bitwise operator.

Let’s assume “a” and “b” are integers numbers and “result” is another integer variable that contains the result of the
computation.

So to compute the minimum number we have to write the below expression.

result = b ^ ((a ^ b) & -(a < b)); // min(a, b)
In above expression,if a < b, then -( a < b) become -1, so it behave like below expression
result = b ^ ((a ^ b) & ~0);
result =  b ^ a ^ b; // b^b is zero
result = a ^ 0; // oring with 0 does not effect
result = a; //minimum number

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Swap two numbers without using a temporary variabl... >>
<< Rotate bits of a number in C?...