码迷,mamicode.com
首页 > 编程语言 > 详细

java位运算笔记

时间:2015-06-27 09:49:51      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:java   位运算   

位运算:
~(非)——》二进制数进行0和1的互换

例子:

public class Test {
	public static void main(String[] args) {
		System.out.println(~-2);//输出1
		System.out.println(~-1);//输出0
		System.out.println(~0);//输出-1
		System.out.println(~1);//输出-2
		System.out.println(~2);//输出-3
		System.out.println(~3);//输出-4
	}
}

技术分享

技术分享


技术分享


^(异或)——》12 ^ 10 = ...01100^01010 =  00110 = 6

例子:

public class Test {
	public static void main(String[] args) {
		int a = 0;
		int b = 0;
		b = a = 12^10;
		System.out.println(a);//输出为 6
		a = a^12;
		System.out.println(a);//输出为 10
		b = b^10;
		System.out.println(b);//输出为 12
	}
}


应用:二个不同的数进行交换

public class Test {
	public static void main(String[] args) {
		int a = 12;
		int b = 10;
		System.out.println(a + "---" + b);// 输出为12---10
		a = a ^ b;
		b = a ^ b;
		a = a ^ b;
		System.out.println(a + "---" + b);// 输出为10---12
	}
}



&(与)——》12 & 10 = ...01100 & 01010 = 01000 = 8

例子:

public class Test {
	public static void main(String[] args) {
		int a = 12;
		int b = 10;
		int c = a&b;
		System.out.println(c);//输出为 8
	}
}


应用:

public class Test {
	public static void main(String[] args) {
		int[] a = new int[2];
		a[0] = 5;
		a[1] = 6;
		for (int i = 0; i < a.length; i++) {
			if ((a[i] & 1) == 1) {// 判断是否为奇数
				System.out.println(a[i] + "奇数");
			} else {
				System.out.println(a[i] + "偶数");
			}
		}
		// 输出为:
		// 5"奇数"
		// 6"偶数"
	}
}


|(或)——》12 | 10 = ...01100 | ...01010 = 01110 = 14

例子:

public class Test {
	public static void main(String[] args) {
		int a = 12;
		int b = 10;
		// ...01100 | ...01010 = 01110 = 14
		int c = a | b;
		System.out.println(c);// 输出为14
	}
}


应用:和位移一起运算可以打包成不同位数的整数

public class Test {
	public static void main(String[] args) {
		int a = 1;
		int b = 2;
		// 256 | 2 = ...01 0000 0000 | ...0010 = ...01 0000 0010 = 258
		int c = a << 8 | b;
		System.out.println(c);// 输出为258
	}
}


>>(右位移)——》12>>2 = 00...01100 >>2 = 00...00011 = 3

-1 >>>24 = 1111...111 >>>24 = 1111...1111 1111 = -1
>>>(无符号)——》 -1 >>> 24 = 1111...111 >>> 24 = 0000...1111 1111 = 255

public class Test {
	public static void main(String[] args) {
		int a = -1;
		// 1111...111 >>> 24 = 0000...1111 1111 = 255
		int b = a>>>24;
		System.out.println(b);// 输出为255
	}
}
12>>2 = 00...01100 >>2 = 00...00011 = 3






版权声明:本文为博主原创文章,未经博主允许不得转载。

java位运算笔记

标签:java   位运算   

原文地址:http://blog.csdn.net/hncu1306602liuqiang/article/details/46657521

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!