Java位运算

Java位运算

  最近看Lucene源代码,发现都是用二进制写文件的,涉及到很多位运算的基础知识,于是恶补一下。

  

private Log log = LogFactory.getLog(TestBitCalculate.class);
	DecimalFormat df = new DecimalFormat("00000000,00000000");
	public void testBitCalculate(){
		Integer i = 5;
		Integer j = 3;
		operate("&", i, j);
		operate("|",i,j);
		operate("^",i,j);
	}
	
	@SuppressWarnings("unused")
	private void operate(String operate,Integer i,Integer j){
		Integer result = 0;
		log.info("-------------------------------");
		log.info(operate + "运算 " + "两个数分别是:" + i + "," + j);
		outPutByBinary(i);
		outPutByBinary(j);
		if(operate.equals("&")){
		   result = i & j;
		}else if(operate.equals("|")){
		   result = i | j;
		}else if(operate.equals("^")){
		   result = i ^ j;
		}
		log.info(result);
		outPutByBinary(result);
		log.info("-------------------------------");
	}
	
	private void outPutByBinary(Integer i){
		log.info(i + "的二进制为:" + df.format(Integer.valueOf(Integer.toBinaryString(i))));
	}

 

程序运行后控制台输出为:

 0    [main] INFO  com.develop.bit.TestBitCalculate  - -------------------------------
0    [main] INFO  com.develop.bit.TestBitCalculate  - &运算 两个数分别是:5,3
0    [main] INFO  com.develop.bit.TestBitCalculate  - 5的二进制为:00000000,00000101
0    [main] INFO  com.develop.bit.TestBitCalculate  - 3的二进制为:00000000,00000011
0    [main] INFO  com.develop.bit.TestBitCalculate  - 1
0    [main] INFO  com.develop.bit.TestBitCalculate  - 1的二进制为:00000000,00000001
15   [main] INFO  com.develop.bit.TestBitCalculate  - -------------------------------
15   [main] INFO  com.develop.bit.TestBitCalculate  - -------------------------------
15   [main] INFO  com.develop.bit.TestBitCalculate  - |运算 两个数分别是:5,3
15   [main] INFO  com.develop.bit.TestBitCalculate  - 5的二进制为:00000000,00000101
15   [main] INFO  com.develop.bit.TestBitCalculate  - 3的二进制为:00000000,00000011
15   [main] INFO  com.develop.bit.TestBitCalculate  - 7
15   [main] INFO  com.develop.bit.TestBitCalculate  - 7的二进制为:00000000,00000111
15   [main] INFO  com.develop.bit.TestBitCalculate  - -------------------------------
15   [main] INFO  com.develop.bit.TestBitCalculate  - -------------------------------
15   [main] INFO  com.develop.bit.TestBitCalculate  - ^运算 两个数分别是:5,3
15   [main] INFO  com.develop.bit.TestBitCalculate  - 5的二进制为:00000000,00000101
15   [main] INFO  com.develop.bit.TestBitCalculate  - 3的二进制为:00000000,00000011
15   [main] INFO  com.develop.bit.TestBitCalculate  - 6
15   [main] INFO  com.develop.bit.TestBitCalculate  - 6的二进制为:00000000,00000110
15   [main] INFO  com.develop.bit.TestBitCalculate  - -------------------------------

你可能感兴趣的:(java,Lucene,J#)