Home  >  Article  >  Java  >  How to calculate left shift operator in java

How to calculate left shift operator in java

DDD
DDDOriginal
2023-10-12 11:22:451492browse

Calculation method: 1. Convert the binary number to be moved into binary format; 2. Move the binary number to the left by the specified number of digits, and fill the right side with zero bits after the move. For example, shift the binary number 1010 to the left by 2 bits to obtain 00101000; 3. Convert the shifted binary number to a decimal number, which is the calculation result of the left shift operator. For example, converting 00101000 to decimal gives 40.

How to calculate left shift operator in java

The left shift operator (<<) in Java shifts a binary number to the left by the specified number of bits and then pads the zero bits on the right . The calculation method of the left shift operator is as follows:

1. Convert the binary number to be moved into binary format.

2. Move the binary number to the left by the specified number of digits, and fill it with zero bits on the right after the movement. For example, shifting the binary number 1010 to the left by 2 bits yields 00101000.

3. Convert the shifted binary number into a decimal number, which is the calculation result of the left shift operator. For example, converting 00101000 to decimal gives 40.

The sample code is as follows:

int num = 10; //The binary number to be moved

int shift = 2; //The number of digits to be moved

int result = num << shift; //The calculation result of the left shift operator

System.out.println(result); //The output result is 40

In this In the example, the binary number 10 is left shifted by 2 bits to obtain 00101000, which is then converted to the decimal number 40, and the final output result is 40.

The above is the detailed content of How to calculate left shift operator in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn