CodeGym /Java 博客 /China /Java 位运算符

Alex Vypirailenko
Java Developer at Toshiba Global Commerce Solutions

Java 位运算符

``````
public class Main {

public static void main(String[] args) {

int x = 342;
System.out.println(Integer.toBinaryString(x));
}
}
``````

101010110
1010 10110（我加了空格是为了方便阅读）是十进制中的数字 342。我们实际上已经把这个数字分解成了单个的比特：0 和 1。对位执行的操作称为按位操作
• ~ — 按位非。

101010110 是用二进制数表示的 342 010101001 是表达式 ~342 的值

``````
public class Main {

public static void main(String[] args) {

int x = 342;
System.out.println(~x);
}
}
``````

169
169 是我们熟悉的十进制系统中的结果 (010101001) :)
• & — 按位与

110110000 是用二进制数表示的 277 1000101011 是用二进制数表示的 432

``````
public class Main {

public static void main(String[] args) {
System.out.println(277&432);
}
}
``````

272
• | — 按位或。

``````
public class Main {

public static void main(String[] args) {
System.out.println(277|432);
}
}
``````

437

• ^ — 按位异或

``````
public class Main {

public static void main(String[] args) {
System.out.println(277^432);
}
}
``````

165

左移

``````
public class Main {

public static void main(String[] args) {
int x = 64;//value
int y = 3;// Shift distance

int z = (x << y);
System.out.println(Integer.toBinaryString(x));
System.out.println(Integer.toBinaryString(z));
}
}
``````

``````
public class Main {

public static void main(String[] args) {
int x = 64;//value
int y = 3;// Shift distance

int z = (x << y);
System.out.println(z);
}
}
``````

512

``````
public class Main {

public static void main(String[] args) {
int x = 64;//value
int y = 26;// Shift distance

int z = (x << y);
System.out.println(z);
}
}
``````

0

``````
public class Main {

public static void main(String[] args) {
System.out.println(111111111 << 3);
}
}
``````
888888888

右移

``````
public class Main {

public static void main(String[] args) {
int x = 64;//value
int y = 2;// Shift distance

int z = (x >> y);
System.out.println(z);
}
}
``````

16

35/2 = 17（去掉余数 1） 17/2 = 8（去掉余数 1）

``````
public class Main {

public static void main(String[] args) {
System.out.println(35 >> 2);
}
}
``````

8

Java 中的运算符优先级

运算符优先级

``````
int x  = 6 - 4/2;
``````

``````
int x  = (6 - 4)/2;
``````

``````
boolean x = 6 - 4/2 > 3 && 12*12 <= 119;
``````
``````
boolean x = 6 - 2 > 3 && 12*12 <= 119;
``````
• 12*12 = 144
``````
boolean x = 6 - 2 > 3 && 144 <= 119;
``````
• 6-2 = 4
``````
boolean x = 4 > 3 && 144 <= 119;
``````

• 4 > 3 = true
``````
boolean x = true && 144 <= 119;
``````
• 144 <= 119 = false
``````
boolean x = true && false;
``````

``````
boolean x = true && false;
boolean x = false;
``````

``````
boolean x = 7 != 6+1;
``````

TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION