Unsigned right shift character, left shift character, signed right shift character in js, java

The shift operation is a regular low shift of the binary. Shift operation can design many wonderful effects, and it is widely used in graphics and image programming.

  • "<<" operator

The "<<" operator performs a left shift operation. During the shift operation, the sign bit always remains unchanged. If there is a vacant position on the right, it is automatically filled with 0; the value beyond 32 bits is automatically discarded.

Move the number 5 to the left by 2 digits, and the return value is 20.

console.log(5 << 2);  //返回值20

  
   
   
  • 1

Use the calculation formula to demonstrate, as shown in the figure.
Insert picture description here

思考:为啥没有<<<呢
因为左位移是填补右边空出的位,符号位不影响它的值哦

  
   
   
  • 1
  • 2
  • ">>" operator

The ">>" operator performs a signed right shift operation. Contrary to the left shift operation, it shifts all the valid bits in the 32-bit number to the right as a whole, and then uses the value of the sign bit to fill the vacant bits . Values ​​exceeded during the movement will be discarded.

Shifting the value of 1000 to the right by 8 bits, the return value is 3.

console.log(1000 >> 8);  //返回值3

  
   
   
  • 1

Use the calculation formula to demonstrate, as shown in the figure.

Insert picture description here

If the value -1000 is shifted to the right by 8 bits, the return value is -4.

console.log(-1000  >> 8);  //返回值 -4

  
   
   
  • 1

Use the calculation formula to demonstrate, as shown in the figure. When the sign bit value is 1, the vacant bits to the left of the valid bit are all filled with 1.

  • ">>>" operator

The ">>>" operator performs a five-symbol right shift operation. It shifts all digits of an unsigned 32-bit integer to the right as a whole. For unsigned or positive shift right operations, the results of unsigned right shift and signed right shift operations are the same.

The return value of the following two lines of expressions is the same.

console.log(1000 >> 8);  //返回值3
console.log(1000 >>> 8);  //返回值3

  
   
   
  • 1
  • 2

For negative numbers, an unsigned right shift will use 0 to fill all the vacancies, and at the same time, the negative number will be treated as a positive number, and the result will be very large. Therefore, be careful when using the unsigned right shift operator to avoid accidental errors .

console.log(-1000 >> 8);  //返回值 -4
console.log(-1000 >>> 8);  //返回值 16777212

  
   
   
  • 1
  • 2

Use the calculation formula to demonstrate, as shown in the figure. The left space is no longer filled with the value of the sign bit, but filled with 0.

Insert picture description here

Guess you like

Origin blog.csdn.net/fxwentian/article/details/115178735