A demo and summary of shift operators in Java

Source: Internet
Author: User

First, there are three shift operators, whose operation type only supports: Byte/short/char/int and long five.

<< left-shift operator, which moves the binary data of the left operand to the left * bit, the empty vacancy is filled with 0, and the extra bit is discarded. ( equal to 2 of the n-th square )

>> Right shift operator, binary data move to the right * bit, after the second binary data erased several? (This is good, but personal understanding) ( equivalent to 2 of the n-th square )

>>> unsigned right-shift operator, regardless of whether the highest bit before the move is 0 or 1, the empty portion of the left-hand side after the right shift is filled with zeros.

Here we take a demo to help understand:

 Public Static voidMain (string[] args) {intA = 16; intb = a << 2;//shift left 2, equivalent to 16 * 2 of 2, that is, the three * 4        intc = a >> 2;//shift right 2, equal to 16/2 of 2, that is, 16/4System.out.println (The binary data for A is: "+integer.tobinarystring (a)); System.out.println ("A after left-shift binary data is:" +integer.tobinarystring (b)); System.out.println ("A after the right shift binary data is:" +integer.tobinarystring (c)); System.out.println ("A value after the left shift is:" +b); System.out.println ("A value after the right shift is:" +c); }}

To view the results of a run:

First, the binary data of 16 is: 10000;

Shift left two bits, 10000 to 10000xx;

Move right two bits, 10000 to 100;

After converting the resulting binary data into normal data,

A value of 64 after the left shift is 16 * 2 2 (16 * 4).

A the value after the right shift is 4, which is 16/2 of the 2-time Square (16/4).

Is it much easier to read this demo and then understand the shift operator?

A demo and summary of 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.