Home  >  Article  >  Java  >  java left shift and right shift

java left shift and right shift

伊谢尔伦
伊谢尔伦Original
2016-11-30 09:40:101816browse

Today I reviewed left shift and right shift in java. Here is an example for negative numbers:

Positive and negative numbers are represented in the form of complement in java

For example -2 is represented in the computer as 11111111 11111111 11111111 11111110

1. Shift left

-2<<2 That is, the result of shifting -2 to the left by 2 bits is: 11111111 11111111 11111111 11111000 (the low bits are complemented with 0)

The above is the complement code, and the highest bit is 1 indicating that this is a negative number. The complement of a negative number is obtained by taking the original code of a positive number: "The highest bit is 1, the remaining bits are inverted, and finally 1 is added."

So by inverting, you can know that the result of -2<<2 actually represents the number 10000000 00000000 00000000 00001000 (-8)

2. Shift right

If the high bit is 1, add 1 to the high bit. If it is 0, add 0

-2>>2: 11111111 11111111 11111111 11111111

10000000 00000000 00000000 00000001 (-1)

3. The shift operator can be combined with "=" to use

a< <=2 means that the value after a is shifted to the left by 2 bits and then assigned to a

4. To add: the Java virtual machine shields the big-endian and little-endian problems, and it is all little-endian internally.


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