Search code examples
javabytebitwise-operatorsbitbit-shift

Why Java isnt calculating logical shift right correctly?


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 :)


Solution

  • 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