package util;
public class BitOperator {
public static void main(String[] args) {
System.out.println("\n按位左移");
output("123", 123);
output("123 << 32", 123 << 32);
System.out.println("\n按位有符号右移");
output("123", 123);
output("123 >> 2", 123 >> 2);
System.out.println("\n按位有符号右移,右移时高位补充符号位");
output("-123", -123);
output("-123 >> 2", -123 >> 2);
System.out.println("\n按位无符号右移");
output("123", 123);
output("123 >>> 1", 123 >>> 1);
System.out.println("\n按位无符号右移,右移时高位补 0");
output("-123", -123);
output("-123 >>> 2", -123 >>> 2);
}
private static void output(String prompt, int result) {
System.out.printf("%10s = %-10d %s%n", prompt, result, toBit(result));
}
public static String toBit(int num) {
char[] chs = new char[39];
for (int i = 0, k = 0; i < Integer.SIZE; i++) {
chs[k++] = (char)('0'+ ((num >>> Integer.SIZE - i - 1) & 1));
if ((i & 3) == 3 && k < chs.length) {
chs[k++] = ' ';
}
}
return new String(chs);
}
}
/*
按位左移
123 = 123 0000 0000 0000 0000 0000 0000 0111 1011
123 << 2 = 492 0000 0000 0000 0000 0000 0001 1110 1100
按位有符号右移
123 = 123 0000 0000 0000 0000 0000 0000 0111 1011
123 >> 2 = 30 0000 0000 0000 0000 0000 0000 0001 1110
按位有符号右移,右移时高位补充符号位
-123 = -123 1111 1111 1111 1111 1111 1111 1000 0101
-123 >> 2 = -31 1111 1111 1111 1111 1111 1111 1110 0001
按位无符号右移
123 = 123 0000 0000 0000 0000 0000 0000 0111 1011
123 >>> 2 = 30 0000 0000 0000 0000 0000 0000 0001 1110
按位无符号右移,右移时高位补 0
-123 = -123 1111 1111 1111 1111 1111 1111 1000 0101
-123 >>> 2 = 1073741793 0011 1111 1111 1111 1111 1111 1110 0001
*/