Is there a way to shift left or right without the byte loss, so that the bytes filled are the ones that are beeing taken?
e.g.:10010 shr 2 => 10100 or: 11001 shl 4 => 11100
the loss of info开发者_运维技巧rmation seems quite inconvenient, since you're not supposed to use it for math anyway..
i just want to send packages over the network in different byte order, so shifting back is important to me
What you're trying to do is bitwise rotation which is supported in Java.
public class Binary {
public static void main(String[] args) {
Integer i = 18;
System.out.println(Integer.toBinaryString(i));
i = Integer.rotateRight(i, 2);
System.out.println(Integer.toBinaryString(i));
}
}
This will print out:
10010
10000000000000000000000000000100
The 2 bits which were shifted off have been rotated round to the start. However there is a lot of 0 padding in the middle because an integer in Java takes up 32 bits.
If you wanted to implement this behaviour yourself, internally it is implemented as:
public static int rotateLeft(int i, int distance) {
return (i << distance) | (i >>> -distance);
}
And:
public static int rotateRight(int i, int distance) {
return (i >>> distance) | (i << -distance);
}
精彩评论