关于Java的移位运算符

/**
 * 测试移位运算符<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();
	}
}

posted on 2013-06-27 17:24  岚之山  阅读(164)  评论(0编辑  收藏  举报

导航