运算符>>和>>>的区别

版权声明:本文为博主原创文章,转载需标明出处。 https://blog.csdn.net/coderDogg/article/details/85208242

观摩ConcurrentHashMap底层代码的时候看到了这段代码:

 /**
     * Returns a power of two table size for the given desired capacity.
     * See Hackers Delight, sec 3.2
     */
    private static final int tableSizeFor(int c) {
        int n = c - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }

一开始没太看懂,后面发现等同于

n == n | n >>> 1;

>>表示是带符号的右移:按照二进制把数字右移指定数位,符号位为正补零,符号位负补一,低位直接移除。

>>>表示无符号的右移:按照二进制把数字右移指定数位,高位直接补零,低位移除。

区别:>>在传递时也把符号一起传递,比如+3、-2在传递再传出时依然是+3、-2,而使用>>>时就会统一变为3、2。带符号于无符号的差别就在此。

猜你喜欢

转载自blog.csdn.net/coderDogg/article/details/85208242