How do shift operators work in Java?

How do shift operators work in Java?

In Java, the shift operators (<<, >>, and >>>) are used to perform bitwise shifts on integer data types, such as int and long. These operators move the bits of a binary number to the left or right, effectively multiplying or dividing the number by powers of 2.

Here's how each shift operator works:

  1. Left Shift (<<):

    • The left shift operator (<<) shifts the bits of a number to the left by a specified number of positions.
    • It effectively multiplies the number by 2 raised to the power of the specified shift count.
    • Bits shifted out on the left are discarded, and zeros are shifted in from the right.

    Example:

    int number = 5; // Binary: 0000 0000 0000 0000 0000 0000 0000 0101 int result = number << 2; // Shift left by 2 positions // Binary result: 0000 0000 0000 0000 0000 0000 0001 0100 // Decimal result: 20 
  2. Right Shift (>>):

    • The right shift operator (>>) shifts the bits of a number to the right by a specified number of positions.
    • It effectively divides the number by 2 raised to the power of the specified shift count.
    • The leftmost bit (the sign bit, in the case of signed data types) is filled with the original value's sign bit (0 for positive, 1 for negative).

    Example:

    int number = 20; // Binary: 0000 0000 0000 0000 0000 0000 0001 0100 int result = number >> 2; // Shift right by 2 positions // Binary result: 0000 0000 0000 0000 0000 0000 0000 0101 // Decimal result: 5 
  3. Unsigned Right Shift (>>>):

    • The unsigned right shift operator (>>>) is similar to the right shift operator (>>), but it always fills the leftmost bits with zeros, regardless of the original value's sign.
    • It effectively divides the number by 2 raised to the power of the specified shift count.

    Example:

    int number = -20; // Binary: 1111 1111 1111 1111 1111 1111 1110 1100 int result = number >>> 2; // Unsigned shift right by 2 positions // Binary result: 0011 1111 1111 1111 1111 1111 1111 0110 // Decimal result: 1073741822 

It's important to note that the behavior of the right shift (>>) operator with signed integers depends on the sign bit. In contrast, the unsigned right shift (>>>) operator always fills with zeros. Shift operators are typically used for low-level bit manipulation, and care should be taken to ensure that they are used correctly to avoid unintended behavior or bugs in your code.


More Tags

having set-intersection richtext landscape-portrait pythagorean classname vue-loader windows-server-2016 msysgit git-difftool

More Java Questions

More Weather Calculators

More Auto Calculators

More Internet Calculators

More Genetics Calculators