java位操作总结

在计算机中所有数据都是以二进制的形式储存的。

位运算其实就是直接对在内存中的二进制数据进行操作,因此处理数据的速度非常快。

方便演示,首先写个二进制打印方法:

private static void printNum(int n){
	String num = Integer.toBinaryString(n);
	if(num.length() == 32){
		System.out.println(num);
	}else{
		StringBuilder sb = new StringBuilder("");
		for(int i =0;i < 32 - num.length(); i ++){
		sb.append("0");
		}
		System.out.println(sb.toString() + num);
	}
}

1、~操作符(取反),对应二进制位取反,0变成1,1变成0

int num = 3;
printNum(num);
printNum(~num);

 结果如下:

00000000000000000000000000000011
11111111111111111111111111111100

 

2、&操作符(与),对应二进制位进行与操作,都为1时变成1,其他变为0

int num1 = 3;
int num2 = 7;
printNum(num1);
printNum(num2);
printNum(num1 & num2);

 

结果如下:

00000000000000000000000000000011
00000000000000000000000000000111
00000000000000000000000000000011

 

3、|操作符(或)对应二进制位进行或操作,都为0时变成0,其他变为1

int num1 = 4;
int num2 = 7;
printNum(num1);
printNum(num2);
printNum(num1 | num2);

 

结果如下:

00000000000000000000000000000100
00000000000000000000000000000111
00000000000000000000000000000111

 

4、^操作符(异或),对应二进制位相同时,该位变成0,否则变成1

int num1 = 5;
int num2 = 9;
printNum(num1);
printNum(num2);
printNum(num1 ^ num2);

 

结果如下:

00000000000000000000000000000101
00000000000000000000000000001001
00000000000000000000000000001100

 

5、<<操作(左移),二进制位向左移动,右边填充0

int num1 = 5;
printNum(num1);
printNum(num1 << 2);

 结果如下:

00000000000000000000000000000101
00000000000000000000000000010100

6、>>操作(右移),二进制位向右移动,左边填充0

int num1 = 5;
printNum(num1);
printNum(num1 >> 2);

 结果如下:

00000000000000000000000000000101
00000000000000000000000000000001

位操作常见应用

1、不使用中间变量交换两个数

int num1 = 2;
int num2 = 5;
num1 = num1^num2;
num2 = num2^num1;
num1 = num1^num2;
System.out.println("num1:" + num1 +"\n"+ "num2:" + num2 );

 2、求2的N次方

//求2的32次方:
System.out.println(Math.pow(2, 32));
System.out.println(1L<<32);

 

3、判断奇数偶数

int num1 = 4;
int num2 = 9;
if(num1%2 == 0){
	System.out.println("偶数");
}else{
	System.out.println("奇数");
}
System.out.println((((int)num1&1) == 1) ? "奇数" : "偶数");
System.out.println((((int)num2&1) == 1) ? "奇数" : "偶数");

 4、求绝对值

int num = -3;
System.out.println(Math.abs(num));
int i = num >> 31;  
System.out.println(i == 0 ? num : (~num + 1));

 

posted @ 2015-05-29 13:04  竹下半碗茶  阅读(...)  评论(...编辑  收藏