JDK源码之Integer类——rotateLeft()方法

rotateLeft()方法的功能是通过将指定int值的二进制补码二进制数左移指定位数获得的值。

所谓的左移如下图所示:

该方法的源码如下:

    /**
     * Returns the value obtained by rotating the two's complement binary
     * representation of the specified {@code int} value left by the
     * specified number of bits.  (Bits shifted out of the left hand, or
     * high-order, side reenter on the right, or low-order.)
     *
     * <p>Note that left rotation with a negative distance is equivalent to
     * right rotation: {@code rotateLeft(val, -distance) == rotateRight(val,
     * distance)}.  Note also that rotation by any multiple of 32 is a
     * no-op, so all but the last five bits of the rotation distance can be
     * ignored, even if the distance is negative: {@code rotateLeft(val,
     * distance) == rotateLeft(val, distance & 0x1F)}.
     *
     * @param i the value whose bits are to be rotated left
     * @param distance the number of bit positions to rotate left
     * @return the value obtained by rotating the two's complement binary
     *     representation of the specified {@code int} value left by the
     *     specified number of bits.
     * @since 1.5
     */
    public static int rotateLeft(int i, int distance) {
        return (i << distance) | (i >>> -distance);
    }

对其进行注释如下:

    /**
     * 返回通过将指定int值的二进制补码二进制数左移指定位数获得的值。 (位从左手移出,或移到高位,在右侧重新移入,或移出低位。)
     * 请注意,向左旋转负距离等效于向右旋转: rotateLeft(val, -distance) == rotateRight(val, distance) 。
     * 还要注意,以32的任意倍数进行旋转都是空操作,因此,即使距离的最后五个位为负数,也可以忽略所有旋转距离,即使该距离是负数: rotateLeft(val, distance) == rotateLeft(val, distance & 0x1F) 。
     * 例如数字987654321的二进制是               0011 1010 1101 1110 0110 1000 1011 0001
     * 调用rotateLeft(987654321,3)方法后二进制是 1101 0110 1111 0011 0100 0101 1000 1001
     *
     * @param i        要向左旋转其位的值
     * @param distance 向左旋转的位的数量
     * @return 通过将指定的int值的二进制补码的二进制补码表示旋转指定的位数而获得的值
     */
    public static int rotateLeft(int i, int distance) {
        /*
            例如:i=987654321, distance=3
            i                                       0011 1010 1101 1110 0110 1000 1011 0001
            i<<distance                             1101 0110 1111 0011 0100 0101 1000 1000
            i >>> -distance                         0000 0000 0000 0000 0000 0000 0000 0001
            (i << distance) | (i >>> -distance)     1101 0110 1111 0011 0100 0101 1000 1001
         */
        // 在移位的时候,如果distance小于0,会根据被移位数的长度进行转换。就比如说这里我们对long进行移位,那么-distance就会被转换成(64 + distance)(注,这里的distance是小于0的)。
        return (i << distance) | (i >>> -distance);// (i >>> -distance)等价于(i >>> 32-distance),注意是因为int是32位,long是64位的
    }

用图来演示该方法的执行如下:

参考文档:

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值