/**
* <br/>
* "<<" : 0<br/>
* ">>" : : 0, 1<br/>
* ">>>" : 0<br/>
*/
public class TestShift {
public static void main(String[] args) {
testLeftShift();
testRightShift();
testUnsignedRightShift();
}
/**
* : 0
*/
public static void testLeftShift(){
int num = -8;
int shift = 2;
leftShift(num, shift);
leftShift(-num, shift);
System.out.println("--------------");
}
/**
* : 0
*/
public static void leftShift(int num, int shift){
// num shift
int r = num << shift;
System.out.println(" : "+ num +" << "+shift);
System.out.println(" :"+binary(num));
System.out.println(" :"+binary(r));
System.out.println("");
}
/**
* :
*/
public static void testRightShift(){
int num = -8;
int shift = 2;
rightShift(num, shift);
rightShift(-num, shift);
System.out.println("--------------");
}
/**
* :
*/
public static void rightShift(int num, int shift){
// num shift
int r = num >> shift;
System.out.println("( ) : "+ num +" >> "+shift);
System.out.println(" :"+binary(num));
System.out.println(" :"+binary(r));
System.out.println("");
}
/**
* : 0
*/
public static void testUnsignedRightShift(){
int num = -8;
int shift = 2;
unsignedRightShift(num, shift);
unsignedRightShift(-num, shift);
System.out.println("--------------");
}
/**
* : 0
*/
public static void unsignedRightShift(int num, int shift){
// num shift
int r = num >>> shift;
System.out.println(" : "+ num +" >>> "+shift);
System.out.println(" :"+binary(num));
System.out.println(" :"+binary(r));
System.out.println("");
}
public static String binary(int i){
return alignRight(Integer.toBinaryString(i),32,'0');
}
/**
*
* @param str
* @param digit
* @param addChar
* @return
*/
public static String alignRight(String str, int digit, char addChar){
str = String.valueOf(str);
digit = digit > 0 ? digit : 0;
StringBuilder builder = new StringBuilder(digit);
builder.append(str);
for (int len = str.length(); len < digit; len++) {
builder.insert(0, addChar);
}
//
return builder.toString();
}
}