简体   繁体   中英

How does Java bit shift operator (>>>) work?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM