The maximum and minimum values of the calculation do not need to be compared twice on the Forum. Some people gave the best answer during the first discussion. That person said that when performing image operations, comparison operations will have a great impact on the efficiency of the command line, and thus require additional implementation. In the second discussion, I couldn't find my first post. So I checked some information and thought about it. I got the previous answer (assuming that Int Is 4 bytes ):
Int min (int A, int B)
{
Int diff = B-;
// B <A: A + (diff &-1)
// B> A: A + (diff & 0)
Return A + (diff & (diff> 31 ));
}
Int max (int A, int B)
{
Int diff = B-;
// B <A: B-(diff &-1)
// B> A: B-(diff & 0)
Return B-(diff & (diff> 31 ));
}
Int ABS (int)
{
Int temp = (A> 31 );
Return (a + temp) ^ temp;
}
There are two main principles:
1. The integer is in the complement representation.
2. The shift operation of the signed number is arithmetic shift (multiplication 2 and Division 2) rather than physical shift.
Positive and 0 complement codes are the same as the original codes. Negative complement codes are the inverse codes of absolute values plus 1. -1 indicates 0 xffffffff.
Any non-negative integer (0 ~ 231-1) 31 digits to the right are 0; any negative integer (-231 ~ -1) 31 digits are shifted to-1. In this way, Min and Max are easier to understand.
Look at abs again
A ^-1 = ~ A
A ^ 0 =
If a is not negative, there is no change; if A is negative, add-1 and then take the inverse to obtain the absolute value.