Java中的移位运算符

1.三种移位运算符

  • 左移:<<

  • 右移:>>

  • 无符号右移:>>>

  • 注:无符号右移表示最高位补零,由于负数在计算机中存储是补码形式(反码+1)

2.案例

  • -15在计算机中存储是ffff,fff1【-15原码为8000,1111(最高位为符号位),取反加1得ffff,fff1(操作时符号位不变)】

  • 正常右移带符号位为ffff,fffc【还原成原码也是取反加一(符号位不变)8000,0003=-3】

  • 无符号右移为3fff,fffc【符号位一起右移两位,多出来的两个最高位补0的3fff,fffc= 1073741820】

public class TestDemo {

    public static void main(String[] args) {

        int i1 = -15 >> 2;
        int i2 = -15 >>> 2;
        
        System.out.println(i1);
        System.out.println(i2);

        System.out.println(Integer.toHexString(i1));
        System.out.println(Integer.toHexString(i2));
    }
}

 

posted @ 2020-03-24 11:00  All_just_for_fun  阅读(352)  评论(0编辑  收藏  举报