Shift operations in Java

Source: Internet
Author: User
Bit manipulation designations in Java include:& | ~ >> << >>>, the first few are very simple, mainly because the operation is more error prone.
1.<<
Logic left, 0 on the right, sign bit and other bits.
Positive:
X<<1 is generally equivalent to 2x, but may overflow.
Overflow range: 230~ (231-1) binary means 010000...000 to 01111 .... 1111, after the shift the highest to become 1, into a negative.
Negative:
X<<1 is also equivalent to 2x, it is possible to overflow.
Overflow range: -231~-(230+1) binary representation 10000 ... 000 to 101111 ... 1111, after the shift the highest to become 0, into a positive.

2.>>
Arithmetic shifts to the right, and does not correspond to the above, when the left is 0 for a positive number, and 1 for the left.
X>>1, the equivalent of X/2, the remainder is discarded, because this is narrowing, so it will not overflow.
But one thing to note: 1 to the right, how many digits are 1.
The remainder that is discarded is positive, and the remainder that 3>>1=1 discards is 1.
The remainder of the -3>>1=-2 is also 1, not 1.
For positive x>>1 and X/2 equality
Negative x>>1 and X/2 are not necessarily equal.

3.>>>
Logical move right, this is the corresponding to the <<
This moves the symbol bit together, 0 on the left.
For positive,>>> and >> is the same
For negative numbers, the right shift is followed by a positive number.

You can use integer.tobinarystring (int i) to see 01 bits, more intuitive.



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.