Shift operators in Java

Source: Internet
Author: User

Keep in mind that all the moving digits are in the complement, so first convert the decimal integer to the complement and then the shift operation.

Shift operation also pay attention to the type of constraints, such as int, moving range is 0-31 bits, so the complement can only see the last five digits, this is a valid number, long moving range is 0-63, so the complement can only see the last six bits.

move the operator right .

Left shift operator (<<): Both the signed number and the unsigned number are low 0.

Signed right shift operator (>>): With symbol extension, 0 for positive high, and 1 for negative high.

Unsigned tips : Shift Assignment

I >>= 10;

The value of I to the right of 10 bits is then assigned to I. Equivalent to: i = i >> 10;.

Shift pretreatment

When a char, byte, Shor type is shifted, it is automatically converted to the int type and then shifted. Since the int type is only 32 bits, when the shift occurs:

I << 127;

, the I of the int type certainly does not move 127 bits to the left, but only the left 32 bits (= 2^5,127 = 1111 1111). Therefore, when the int type shifts, the shift number is only 5 bits low. Similarly, when a long is shifted, the shift number is only 6 bits low.

Instance:

public class Main {public static void main(String[] args) {System.out.println(1 << -2);System.out.println(1 << 30);System.out.println(1L << -2);System.out.println(1L << 62);}}

1073741824107374182446116860184273879044611686018427387904


int is a 32-bit, long is 64-bit, moving negative digits or exceeding the number of digits should take the remainder to 0~31, 0~63.

Shift operators in Java

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.