Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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')+")");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading