1

在下面的代码中,我到底在哪里做错了什么?将数据旋转回左侧时,我得到了意外的值。解决方法是什么?

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);
    }
}
4

2 回答 2

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)));
}

参考这个问题。应用于字节变量的无符号右移行为

发生这种情况是因为在移位操作发生之前字节被转换为有符号整数。

于 2013-10-04T12:59:23.583 回答
1

当前的答案对我不起作用,我意识到这是因为运算符的右侧应该移动整数(32)而不是 8 的大小。这是因为字节在任何之前被提升为整数在其上进行的转移操作。这是我的解决方案:

  /**
 * Performs a circular bitwise rotation on a byte, rotating right by shift positions.
 *
 * @param bits the byte to rotate
 * @param shift the number of positions to rotate by
 * @return the rotated byte
 */
private static byte rotateRight(byte bits, int shift) {
    return (byte) (((bits & 0xff) >>> shift) | ((bits & 0xff) << (Integer.SIZE - shift)));
}

/**
 * Performs a circular bitwise rotation on a byte, rotating left by shift positions.
 *
 * @param bits the byte to rotate
 * @param shift the number of positions to rotate by
 * @return the rotated byte
 */
private static byte rotateLeft(byte bits, int shift)
{
    return (byte)(((bits & 0xff) << shift) | ((bits & 0xff) >>> (Integer.SIZE - shift)));
}

这是一个旧线程,但希望有人能找到这个答案有用!

于 2022-02-12T21:51:01.067 回答