package util;
public class BitOperator {
public static void main(String[] args) {
System.out.println("
");
output("123", 123);
output("123 << 32", 123 << 32);
System.out.println("
");
output("123", 123);
output("123 >> 2", 123 >> 2);
System.out.println("
, ");
output("-123", -123);
output("-123 >> 2", -123 >> 2);
System.out.println("
");
output("123", 123);
output("123 >>> 1", 123 >>> 1);
System.out.println("
, 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
*/