Sud*_*ali 1 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);
}
}
Run Code Online (Sandbox Code Playgroud)
以下作品.
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)));
}
Run Code Online (Sandbox Code Playgroud)
请参阅此问题.无符号右移的行为应用于字节变量
发生这种情况是因为在移位操作发生之前,字节将转换为signed int.