Java基礎-位運算符Bitwise Operators程序員
做者:尹正傑面試
版權聲明:原創做品,謝絕轉載!不然將追究法律責任。spa
一.位運算特色code
位運算符分爲按位與(&),按位或(|),按位異或(^),按位取反(~)。blog
位運算存在如下特色:it
1>.若是&|^兩側爲布爾值,就是邏輯操做io
若是兩側爲整數就是按位操做class
2>.位運算就是對整數的二進制位進行運算基礎
a>.1 & 1 == 1 變量
b>.0 | 0 == 0
c>.1 ^ 1 == 1
d>.1 ^ 1 == 1
e>.~1 == 0
f>.~0 == 1
二.案例展現
1.用法展現
1 /* 2 @author :yinzhengjie 3 Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/ 4 EMAIL:y1053419035@qq.com 5 */ 6 7 public class bitwise{ 8 public static void main(String[] args){ 9 int a = 10; 10 int b = 20; 11 int c = a & b; 12 System.out.println("c==" + c); //c == 0 13 /** 14 a變量的值10,它對應的二進制形式爲: 15 00000000 00000000 00000000 00001010 16 a變量的值20,它對應的二進制形式爲: 17 00000000 00000000 00000000 00010100 18 按位與& 19 -------------------------------------------- 20 00000000 00000000 00000000 00000000 21 */ 22 23 24 c = a | b; 25 /** 26 a變量的值10,它對應的二進制形式爲: 27 00000000 00000000 00000000 00001010 28 a變量的值20,它對應的二進制形式爲: 29 00000000 00000000 00000000 00010100 30 按位或| 31 -------------------------------------------- 32 00000000 00000000 00000000 00011110 33 */ 34 System.out.println("c==" + c); //c == 30 35 36 c = a ^ b; 37 /** 38 a變量的值10,它對應的二進制形式爲: 39 00000000 00000000 00000000 00001010 40 a變量的值20,它對應的二進制形式爲: 41 00000000 00000000 00000000 00010100 42 按位異或^ 43 -------------------------------------------- 44 00000000 00000000 00000000 00011110 45 */ 46 System.out.println("c==" + c); //c == 30 47 48 49 c = ~a; 50 /** 51 a變量的值10,它對應的二進制形式爲: 52 00000000 00000000 00000000 00001010 53 按位取反(~) 54 -------------------------------------------- 55 11111111 11111111 11111111 11110101 56 */ 57 System.out.println("c==" + c); c == -11 58 59 60 } 61 }
2.面試題來襲
1 /* 2 @author :yinzhengjie 3 Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/ 4 EMAIL:y1053419035@qq.com 5 */ 6 7 public class bitwise{ 8 public static void main(String[] args){ 9 //若是實現兩個數的原地交換,不借助與第三個變量,實現兩個數的交換 10 int x = 10; 11 int y = 20; 12 13 //方案一: 14 x = x + y; //x = 30 15 y = x - y; //y = 10 16 x = x - y; //x = 20 17 System.out.println("x== " + x + ",y== " + y); 18 19 20 //方法二: 21 x = 10; 22 y = 20; 23 x = x ^ y; //x == 30 24 y = x ^ y; //y == 10 25 x = x ^ y; //x == 20 26 System.out.println("x== " + x + ",y== " + y); 27 28 29 //實際應用中,實現兩個數的交換,建議使用如下方法,方便其它程序員能夠讀懂 30 x = 10; 31 y = 20; 32 int temp = x ; 33 x = y; 34 y = temp; 35 36 System.out.println("x== " + x + ",y== " + y); 37 38 } 39 }