0
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?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • As a is negative, I think that the javadocs answers your question. *The unsigned integer value is the argument plus 2pow(32) if the argument is negative;** – Scary Wombat Aug 09 '23 at 06:22
  • why do you expect `001111111111111111111111111101` with 30 digits and not `00111111111111111111111111111101` with 32 digits (or `111111111111111111111111111101` with 30 digits) ?? An `int` has 32 bits but `toBinaryString()` does not *show* leading zeros – user16320675 Aug 09 '23 at 06:27
  • maybe the output from that [code](https://ideone.com/gVC20K) is better to see the problem – user16320675 Aug 09 '23 at 06:38

1 Answers1

1

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')+")");
Thomas Kläger
  • 17,754
  • 3
  • 23
  • 34