-2

The output I calculated from right shifting the 2's complement of 20 and then converting the result to decimal does not match the output. Why does the code below generate such unexpected output?

class OperatorExample{  
    public static void main(String args[]){  

        System.out.println(-20>>>2);  
    } 
}

output: 1073741819
bee_girl
  • 3
  • 4

1 Answers1

2

The calculation is:

Take -20:

jshell> Integer.toBinaryString(-20)
$1 ==> "11111111111111111111111111101100"

Shift it right by 2, which removes the last two zeros:

jshell> Integer.toBinaryString(-20 >>> 2)
$2 ==> "111111111111111111111111111011"

And convert it to decimal:

jshell> 0b111111111111111111111111111011
$3 ==> 1073741819
Joni
  • 108,737
  • 14
  • 143
  • 193