search
HomeJavajavaTutorialDetailed explanation of java shift operator

Java shift operators are nothing more than these three: > (signed right shift) and >>> (unsigned right shift).
1. Left shift operator
Left shift operator 1) Its general format is as follows:
value num specifies the number of bits to shift the value value.
Just remember one thing about the rules of left shift: discard the highest bit and fill the lowest bit with 0
If the number of bits moved exceeds the maximum number of bits of the type, the compiler will take modulo of the number of bits moved. For example, if the int type is moved by 33 bits, only 332=1 bit is actually moved.

2) Operation rules
Move all numbers to the left by the corresponding number of digits in binary form, shift out the high bits (discard), and fill the empty bits in the low bits with zeros.
When the operand of the left shift is of type int, every time it moves 1 bit, its 31st bit will be shifted out and discarded;
When the operand of the left shift is of type long, every time it moves 1 bit, its 63rd bit will be to be removed and discarded.
When the left-shift operand is of byte and short type, these types will be automatically expanded to int type.

3) Mathematical meaning
On the premise that the number does not overflow, for positive and negative numbers, shifting one position to the left is equivalent to multiplying by 2 raised to the power of 1, and shifting n bits to the left is equivalent to multiplying by 2 raised to the nth power.

4) Calculation process:
For example: 3 1) Convert 3 into a binary number 0000 0000 0000 0000 0000 0000 0000 0011,
2) Convert the high bit of the number (left side) ) are moved out, and all other numbers are shifted 2 bits to the left.
3) Fill in the two empty positions with zeros in the low bits (right). The final result obtained is 0000 0000 0000 0000 0000 0000 0000 1100, which converted to decimal is 12.

The number of bits moved exceeds the maximum number of bits for the type.

If the number is shifted into higher-order bits (31 or 63 bits), the value will become negative. The following program illustrates this:

// Left shifting as a quick way to multiply by 2.

public class MultByTwo {
public static void main(String args[]) {
int i;
int num = 0xFFFFFFE;
for(i=0; i num = num System.out.println(num);
}
}
}

The output of this program is as follows:

536870908

1073741816
2147483632
-32
Note: n-bit binary, the highest bit is the sign bit, so the numerical range represented is -2^(n-1) ——2^(n-1) -1, so the modulus is 2^(n-1).

2. Right shift operator

Right shift operator 1) Its general format is as follows:
value >> num
num specifies the number of bits to shift the value value.
Just remember one thing about the rules of right shift: the sign bit remains unchanged, and the sign bit is added to the left

2) Operation rules:

Move all numbers to the right in binary form by the corresponding number of digits, shift out the low bits (discard), and high bits The empty bits are filled with sign bits, that is, positive numbers are filled with zeros, and negative numbers are filled with 1. When the operands of the right shift are byte and short types, these types will be automatically expanded to int type.
For example, if the value to be removed is a negative number, 1 is added to the left for each right shift. If the value to be removed is a positive number, 0 is added to the left for each right shift. This is called sign bit extension (sign preservation). bit) (sign extension), used to maintain the sign of negative numbers when performing a right shift

operation.

3) Mathematical meaning

Shifting one bit to the right is equivalent to dividing by 2, and shifting to the right by n bits is equivalent to dividing by 2 raised to the nth power.

4) Calculation process

11 >>2 (11 is int type)

1) The binary form of 11 is: 0000 0000 0000 0000 0000 0000 0000 1011
2) Move out the last two digits of the low digits, because the The number is positive, so zeros are padded in the high bits.
3) The final result is 0000 0000 0000 0000 0000 0000 0000 0010.
Converted to decimal is 3.

35 >> 2 (35 is int type)

35 converted to binary: 0000 0000 0000 0000 0000 0000 0010 0011

Move out the last two digits of the low bits: 0000 0000 0000 0000 0000 0000 0000 1000
Convert to decimal : 8

5) The sign is not retained when shifting right

The value after right shifting is bitwise ANDed with 0x0f, so that any sign bit extension can be discarded, so that the obtained value can be used as the subscript of the defined array, Thus, the hexadecimal character represented by the corresponding array element is obtained.

For example
public class HexByte {
public static public void main(String args[]) {
char hex[] = {
'0', '1', '2', '3', '4', '5 ', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', ​​'f''
};
byte b = (byte) 0xf1;
System.out.println("b = 0x" hex[(b >> 4) & 0x0f] hex[b & 0x0f]);}}

(b >> 4) The operation process of & 0x0f: The binary form of

b is: 1111 0001

The 4-digit number is shifted out: 0000 1111
Bitwise AND operation: 0000 1111
Converted to the decimal form: 15
The operation process of

b & 0x0f: The binary form of
b is: 1111 0001
The binary form of 0x0f is: 0000 1111
Bitwise AND operation: 0000 0001
Converted to the decimal form: 1

So, this program The output of Specifies the number of bits to shift the value value.
Just remember one thing about the rules of unsigned right shift: ignore the sign bit extension and fill the highest bit with 0

The unsigned right shift operator>>> only makes sense for 32-bit and 64-bit values ​​








For more detailed explanations of Java shift operators and related articles, please pay attention to 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
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment