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

この質問を参照してください。バイト変数に適用される符号なし右シフトの動作

これは、シフト操作が行われる前にバイトが signed int に変換されるために発生します。

于 2013-10-04T12:59:23.583 に答える
1

現在の答えは私にはうまくいきませんでした.演算子の右側が8ではなく整数(32)のサイズだけシフトする必要があるためだと気付きました.その上で行われるシフト操作。これが私の解決策です:

  /**
 * 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 に答える