"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Shift operators and bitwise shorthand assignments

Shift operators and bitwise shorthand assignments

Published on 2024-11-05
Browse:680

1. Bit Shift Operators

  • >>: Shift to the right.
  • >>>: Unsigned right shift (zero-padded).

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

3. Left Shift

  • 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 at 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 at each shift, with rounding down.

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

  • No sign bit preservation; 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 out-shifted bits.

Example:
Left and Right Shift
*ShiftDemo *

Care when Shifting Byte and Short Values

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

Example:

  • Move a negative byte value to the right: when promoted to int, high-order bits are padded 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 bitwise binary operators have a shorthand form that combines an assignment with the bitwise operation.

Example

x = x ^ 127;
x ^= 127;

Os operadores de deslocamento e atribuições abreviadas bitwise

Release Statement This article is reproduced at: https://dev.to/devsjavagirls/os-operadores-de-deslocamento-e-atribuicoes-abreviadas-bitwise-3nao?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3