Bit Operations implement int ABS/MIN/Max Functions

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.