Why doesn't this code output the way I think? (about shift)

    public static void maain(String[] args){
        int a = -11;
        System.out.println(" a= "+a+"("+Integer.toBinaryString(a)+")");
        System.out.println(" a>>2= "+(a>>2)+"("+Integer.toBinaryString(a>>2)+")");
        System.out.println(" a>>>2= "+(a>>>2)+"("+Integer.toBinaryString(a>>>2)+")");
}

i think a>>>2 output is 001111111111111111111111111101
Because >>> means shift right and fill blanks with 0
am i thinking wrong?

>Solution :

Why do you think that Integer.toBinaryString() outputs leading zeros? The documentation clearly states otherwise:

If the unsigned magnitude is zero, it is represented by a single zero character ‘0’ (‘\u0030’); otherwise, the first character of the representation of the unsigned magnitude will not be the zero character.

Java doesn’t offer a built-in method to convert an integer into a binary representation with leading zeros. Several possible solutions are offered at How to get 0-padded binary representation of an integer in java?

For example you could use:

System.out.println(" a>>>2= "+(a>>>2)+"("+String.format("%32s", Integer.toBinaryString(a>>>2)).replace(' ', '0')+")");

Leave a Reply