On the difference of unsigned right shift

Regarding the problem of unsigned displacement, when I was studying in university, I knew that for unsigned displacement, just whether it is positive or negative, it will get a positive number. Today I happened to see a problem that puzzled me [basic] Not strong, the ground shakes the mountains, it’s terrible]

public class BitOperation {
    
    
    public static void main(String[] args) {
    
    
    //在这里我们假定设i的值为-10
         int i = -10;
    //无符号右移两位
         int j = i>>>2;
     //输出结果
        System.out.println("无符号位移的值为:"+j);
    }
}

According to the previous analysis as follows

public class BitOperation {
    public static void main(String[] args) {
         int i = -10;
      //二进制表示:
        // 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0
        //右移两位,前面会补零 得到 :
        // 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0
        //然后计算得到536870914
         int j = i>>>2;
        System.out.println("无符号位移的值为:"+j);
    }
}

But the result is

public class BitOperation {
    
    
    public static void main(String[] args) {
    
    
    //在这里我们假定设i的值为-10
         int i = -10;
    //无符号右移两位
         int j = i>>>2;
     //输出结果
        System.out.println("无符号位移的值为:"+j);
    }
}

console
无符号位移的值为:1073741821

why is that?

在计算机内部数字的存储是以二进制的补码来进行存储的,也就是说,对于-10
原码 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0
反码 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 0 1
补码 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 0
接着进行无符号右移两位
得到 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1
因为正数的原码=补码=反码,所以得到的即为无符号位移的结果。

When you have time, you can take a look at the data structure and computer composition principles. If the foundation is not firmly shaken, you will be surprised when you work! ! !

Guess you like

Origin blog.csdn.net/MAKEJAVAMAN/article/details/106817135