工作笔记(四)

2019-08-20  本文已影响0人  overflow_e4e4

今天看到一个移位操作符的运用1<<-1,一般移位操作数都是正数,看到后这个操作数是-1后先是惊讶,然后陷入思考,因为这段代码并没有语法上错误,那么<<-1到底是什么操作?

1. 猜想

是不是等同于1>>1,我猜想左移-1位就是右移1位,看似很合理,于是写了一段测试代码:

 public static void main(String[] args) {
        int a =6;


        System.out.println(a<<-2);

        System.out.println(a>>2);
    }

输出结果:


输出结果

从结果看,猜想是错误的。

2. 答案

If the promoted type of the left-hand operand is int, then only the five lowest-order bits of the right-hand operand are used as the shift distance. It is as if the right-hand operand were subjected to a bitwise logical AND operator & (§15.22.1) with the mask value 0x1f (0b11111). The shift distance actually used is therefore always in the range 0 to 31, inclusive.

这段话意思是当左手操作数是int时候,int总有32位,所以右手操作符总在031之间,并且以二进制0b11111为掩码,所以此时-1相当于31

问题解决了:1<<-1 等同1<<31

上一篇 下一篇

猜你喜欢

热点阅读