Java的位運算符有:&與、|或、^異或、~非、<<算術左移、>>算術右移、>>>邏輯右移
1. &(與)
全是1-->1
全是0-->0
有1有0-->0
例:000 111 010 101
000 111 101 101
----------------------------
000 111 000 101
1 int i = 1; //00000000000000000000000000000001 2 int j = 2; //00000000000000000000000000000010 3 int n = i&j;//00000000000000000000000000000000 4 System.out.println(n);//0
2. |(或)
有1-->1
全0-->0
例:000 111 010 101
000 111 101 010
----------------------------
000 111 111 111
int i = 1; //00000000000000000000000000000001 int j = 2; //00000000000000000000000000000010 int n = i|j;//00000000000000000000000000000011 Sys.out.println(n);//3
3. ^(異或)
全0-->0
全1-->0
有1有0-->1
例:000 111 010 101
000 111 101 010
----------------------------
000 000 111 111
int i = 1; //00000000000000000000000000000001 int j = 2; //00000000000000000000000000000010 int n = i^j;//00000000000000000000000000000011 System.out.println(n);//3
4. ~(非)
把0變1
把1變0
例:000 111 010 101
----------------------------
111 000 101 010
int i = 1; //00000000000000000000000000000001 int j = ~i;//11111111111111111111111111111110 System.out.println(j);//-2
5. <<(左移)
x<<n
把x向左邊平移n位。
int i = 2147483647; //01111111111111111111111111111111 int j = i<<1; //111111111111111111111111111111110 System.out.println(j);//-2
6. >> (右移)
x<<n
把x向右邊平移n位。如圖:
int i = 2147483647;//01111111111111111111111111111111 int j = i>>1; //00111111111111111111111111111111 int o = -2147483647;//10000000000000000000000000000001 int k = o>>1; //11000000000000000000000000000000 System.out.print(j);//1073741823 System.out.print(k);//-1073741823 int n = i>>32; System.out.print(n);//2147483647 >>>、>>和<<,如果移動了大於該類型的最大位數,移動位數就會被取模。這裡實際移動了32%32=0
7. >>> (邏輯右移)
x>>>n
將x向右平移n位。正負均補0。
int i=2147483647;//01111111111111111111111111111111 int j=i>>>1; //00111111111111111111111111111111 int o=-2; //11111111111111111111111111111110 int k=o>>>1; //01111111111111111111111111111111 System.out.println(j);//1073741823 System.out.println(k);//2147483647