0

I just learned about logical shift right. Why my java isnt calculating it correctly? Example:

public class Operators {

    public static void main(String[] args) {
        byte z = -16;
        System.out.println((z >>> 2));
    }    
}

Why Java output: 1073741820

-16 = 1111 0000
-16 >>> 2 = 0011 1100 = 60

Thanks for the help :)

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
  • 1
    `System.out.println(Integer.toBinaryString(z >>> 2));` – Elliott Frisch Feb 26 '20 at 22:08
  • 1
    Did you expect `System.out.println((byte) (z >>> 2));` ? – Elliott Frisch Feb 26 '20 at 22:10
  • 2
    Because byte, short and int all get operated on as int. (https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.6.1) – Dawood ibn Kareem Feb 26 '20 at 22:20
  • Questions like "why is Java wrong" are often med with negative reactions because it's perceived as somewhat mislead when an unwelcome behaviour is observed and it's assumed that the hundreds of engineers who built, tested and improved the base system are more likely to have made a basic, obvious mistake than that *you* made a mistake and/or misinterpreted something. Phrasing it like "Why isn't this behaving the way I expect it" the next time would be appreciated, thanks! – Joachim Sauer Feb 27 '20 at 16:22

1 Answers1

1

The unsigned right shift operator >>> do not use the sign bit to fill the trailing positions. It always fills the trailing positions by 0.

public class Main {
    public static void main(String[] args) {
        String s = "00000000000000000000000000000000";
        byte z = -16;
        System.out.println("z in decimal: " + z + ",              binary: " + s.substring(Integer.toBinaryString(z).length())
                + Integer.toBinaryString(z));
        System.out.println("z >>> 1 in decimal: " + (z >>> 1) + ", binary: "
                + s.substring(Integer.toBinaryString(z >>> 1).length()) + Integer.toBinaryString(z >>> 1));
        System.out.println("z >>> 2 in decimal: " + (z >>> 2) + ", binary: "
                + s.substring(Integer.toBinaryString(z >>> 2).length()) + Integer.toBinaryString(z >>> 2));
    }
}

Output:

z in decimal: -16,              binary: 11111111111111111111111111110000
z >>> 1 in decimal: 2147483640, binary: 01111111111111111111111111111000
z >>> 2 in decimal: 1073741820, binary: 00111111111111111111111111111100
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110