圆形旋转:向左旋转发出问题

时间:2013-10-04 12:39:45

标签: java data-structures

在下面的代码中,我在哪里以及究竟做错了什么?将数据向左旋转时,我得到了意想不到的值。有什么办法解决这个问题?

public class RotateExample {
    public static byte rotateRight(byte bits, int shift) {
        return (byte)((bits >>> shift) | (bits << (8 - shift)));
    }

    public static byte rotateLeft(byte bits, int shift) {
        return (byte)((bits << shift) | (bits >>> (8 - shift)));
    } 

    public static void main(String[] args)  {
        //test 1 failed
        byte a = (byte)1;
        byte b = rotateRight(a,1);
        byte c = rotateLeft(b,1);
        System.out.println(a+" "+b+" "+c);

        //test 2 passed
        a = (byte)1;
        b = rotateRight(a,2);
        c = rotateLeft(b,2);
        System.out.println(a+" "+b+" "+c);

        //test 3 failed
        a = (byte)2;
        b = rotateRight(a,2);
        c = rotateLeft(b,2);
        System.out.println(a+" "+b+" "+c);

        //test 4 passed
        a = (byte)2;
        b = rotateRight(a,3);
        c = rotateLeft(b,3);
        System.out.println(a+" "+b+" "+c);
    }
}

1 个答案:

答案 0 :(得分:6)

以下作品。

public static byte rotateRight(byte bits, int shift)
{
     return (byte)(((bits & 0xff)  >>> shift) | ((bits & 0xff) << (8 - shift)));
}
public static byte rotateLeft(byte bits, int shift)
{
    return (byte)(((bits & 0xff) << shift) | ((bits & 0xff) >>> (8 - shift)));
}

参考这个问题。 Behaviour of unsigned right shift applied to byte variable

这是因为在转换操作发生之前,字节将转换为signed int。