2013-10-04 5 views
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); 
    } 
} 

답변

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

이는 시프트 연산이 일어나기 전에 바이트가 부호있는 int로 변환되기 때문에 발생합니다.

+0

나는 그것을 얻었다 ... 당신이 저와 공유 한 다른 이야기 스레드를위한 감사합니다. –

+0

고마워요! 이유는 모르겠지만 작동하는 것 같습니다. :) 각 메소드의 첫 번째 줄에 다음을 추가해야했습니다. 'shift = shift % 8'. 나는이 메소드가'int'가 의미있는 범위 (0에서 8)에 있다고 가정합니다. –