Shift right instead of dividing the power by 2

Source: Internet
Author: User

When it is positive, there is no problem.

But when it is negative, the result is correct for situations where rounding is not required. However, when the rounding is needed, the shift causes the result to be rounded down instead of rounding to 0 as the rule requires. For example, 7/2 should get-3 instead of-4.

Rule of Use: for integers x and any y > 0, there is "x/y = (x + y-1)/y". Round up, rounding down

Suppose X=ky+r, here 0≤r<y, gets (x+y-1)/y=k+ (r+y-1)/y, so (x+y-1)/y"=k+ (r+y-1)/y". When r=0, the following item equals 0, and when R > 0 o'clock, equals 1. That is, by adding a partial y-1 to X and then rounding the division down, when y divides x, we get k, otherwise we get K + 1. Therefore, for x < 0, if you precede the right shift with X plus (1<<k)-1, then we will get the result of rounding correctly.

Also that is: X is a negative number, Y/x should be equal to "x/y = (x + y-1)/y", but the right shift is actually rounded down ", so just equivalent to (x + y-1) Right shift

This analysis shows that for positive negative numbers using right shift instead of division, they can be represented as (x<0? x+ (1<<k)-1): x) >>k

Excerpt from: "In-depth understanding of computer systems" 2.3.7 divided by 2 power

Shift right instead of dividing the power by 2

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.