------- android培训、java培训、期待与您交流! ----------
此次,通过两道练习题来了解一下位运算符。
1、最有效率的算出2*8的值。
2、对两个整数变量的值进行互换。
……………………………………………………………………
1、2*8的值可通过*直接得出,代码如下:
class Operate { public static void main(String[] args) { int sum; sum = 2*8; System.out.println("2*8="+sum); } }
然而,这样的效率并不是最有效率的,电脑中CPU运行都是计算而二进制,使用位运算符“>>”直接进行移位运算是最有效率的,代码如下:
class Operate { public static void main(String[] args) { int sum; sum = 2<<3; System.out.println("2*8="+sum); } }
2<<3,即2左移3位,也就是2*2^3,从而得出2*8的值。
如果是2>>1,就相当于2/2^1,也就是1.因为元素均为整形,因此如果是6>>2,那么结果就是1了,因为6/4,取整的缘故。
右移分为“>>”、“>>>”两种,>>进行移位时,左边的空位依据最高位进行0或1.如果是负数,就补1,;若是正数,就补0.而对于>>>,无论正负,左边空位一律补0。
……………………………………………………………………
2、对两个整数的值进行互换,方法有许多。
(1)通过中间值进行互换,代码如下:class Swap1 { public static void main(String[] args) { int x = 1, y = 6; System.out.println("x="+x+",y="+y); int tmp; tmp = x; x = y; y = tmp; System.out.println("x="+x+",y="+y); } }
此方法是最常见的方法,思路简单,常用于软件开发中。(2)通过+、-进行互换,代码如下:class Swap2 { public static void main(String[] args) { int x = 1, y = 6; System.out.println("x="+x+",y="+y); x = x+y; y = x-y; x = x-y; System.out.println("x="+x+",y="+y); } }
此方法较为巧妙,避免了第3变量,但是当x、y很大时,x+y可能会出现损失精度。(3)通过异或运算“^”进行互换,代码如下:class Swap3 { public static void main(String[] args) { int x = 1, y = 6; System.out.println("x="+x+",y="+y); x = x^y; y = x^y;//x^y^y=x x = x^y;//x^y^x=y System.out.println("x="+x+",y="+y); } }
原理为x^y^y=x,此原理常用于加密中。异或(^)运算过程如下:x=1:0001 y=6:0110x^y=0001^0110------0111x^y^y=0111^0110------0001 = x