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