Home> Java> javaTutorial> body text

Shift operators and bitwise shorthand assignments

王林
Release: 2024-08-17 18:48:32
Original
243 people have browsed it

1. Bit Shift Operators

  • <<: Shift left.
  • >>: Shift to the right.
  • >>>: Unsigned right shift (with zero padding).

2. General Syntax of Shift Operators
value << num-bits: Shifts the value bits to the left.
value >> num-bits: Shifts the value bits to the right, preserving the sign bit.
value >>> num-bits: Shifts the value bits to the right, inserting zeros on the left.

3. Shift to the Left

  • Each shift to the left causes all bits of the value to be shifted one position to the left.
  • A 0 bit is inserted to the right.
  • Effect: Multiplication of the value by 2 with each shift.

4. Shift to the Right

  • Each right shift moves all bits one position to the right.
  • The sign bit is preserved: 0 for positive values and 1 for negative values.
  • Effect: Divide the value by 2 for each shift, with rounding down.

5. Shift to the Right No Signal (>>>)

  • No preservation of the signal bit; inserts 0 on the left.
  • Used in bit patterns where the value is treated as an unsigned number.

6. Displacement is not rotational

  • Bits shifted out are lost.
  • Shifting does not allow recovery of bits shifted out.

Example:
Scrolling Left and Right
*ShiftDemo *

Care when Shifting Byte and Short Values

  • Java automatically promotes byte and short to int when evaluating an expression.

Example:

  • Shifting a negative byte value to the right: when promoted to int, higher order bits are filled with 1.
  • When shifting right with zero padding (>>>), this can cause problems as the top 24 bits will be 1 before zeros start to appear.

Abbreviated Assignments with Bitwise Operators

  • All binary bitwise operators have a shorthand form that combines an assignment with the bitwise operation.

Example

x = x ^ 127; x ^= 127;
Copy after login
e

Os operadores de deslocamento e atribuições abreviadas bitwise

The above is the detailed content of Shift operators and bitwise shorthand assignments. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!