Why is the mean used in Java (Low+high) >>>1 instead of (Low+high)/2 or (Low+high) >>1 to calculate the average? Fortunately, where?

Source: Internet
Author: User
Tags bitwise operators


>>> and >> are bitwise operators, only valid for integral types (not for floating-point types).
When the integer type (low+high) >>1 can replace (Low+high)/2.
>>> is the unsigned right-shift operator. If Low+high is a positive integer, these three operations are equivalent.
Because of compiler optimizations, their efficiency should be the same (if there is no compiler optimization, the shift operation is faster).
Use >>> generally have a special purpose

As for the difference between >>> and >>, it is signed and unsigned. For example, the result of -2>>>1 is 2147483647, and -2>>1 's result is-1. (where 2147483647 is-2 of the complement right moves one after the left 0 results.) )

Here the average value is calculated using >>> replacing >&gt, I'm afraid because there may be a large number, these numbers alone will not exceed integer.max_value, but may be exceeded after summing, if using >> or/to calculate, Negative results are calculated as a result of overflow.

Use the following procedure to illustrate the problem:
private static void Testfun () {
int low = Integer.max_value;
int high = Integer.max_value;
System.out.println ("Low:" + low); Take a look at the numbers first
int as = (low + high) >> 1;
int div = (low + high) >> 1;
int au = (low + high) >>> 1;
System.out.println ("as:" + as); Use >> to calculate the average, and/the same.
System.out.println ("div:" + div); Use >> to calculate the average, and/the same.
System.out.println ("au:" + au); Use the average of >>> calculations.
}

Execution Result:
low:2147483647
As:-1
Div:-1
au:2147483647

Why is the mean used in Java (Low+high) >>>1 instead of (Low+high)/2 or (Low+high) >>1 to calculate the average? Fortunately, where?

Why is the mean used in Java (Low+high) >>>1 instead of (Low+high)/2 or (Low+high) >>1 to calculate the average? Fortunately, where?

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.