java中int 类型的移位运算与位运算

移位运算

在计算机中,int类型是以二进制的形式展示的,如9表示为:

00000000 0000000 0000000 00001001

int类型可进行移位运算,如:

int n = 7; // 00000000 00000000 00000000 00000111 = 7

int a = n << 1; // 00000000 00000000 00000000 00001110 = 14

int b = n << 2; // 00000000 00000000 00000000 00011100 = 28

int c = n << 28; // 01110000 00000000 00000000 00000000 = 1879048192

int d = n << 29; // 11100000 00000000 00000000 00000000 = -536870912

当左移29位时,由于最高位变成1,因此结果变成了负数。

位运算

一共四种,分别为&(且)、|(或)、~(非)、^(异或)

x = 0 & 0; // 0
x = 0 & 1; // 0
x = 1 & 0; // 0
x = 1 & 1; // 1
n = 0 | 0; // 0
n = 0 | 1; // 1
n = 1 | 0; // 1
n = 1 | 1; // 1
n = ~0; // 1
n = ~1; // 0
n = 0 ^ 0; // 0
n = 0 ^ 1; // 1
n = 1 ^ 0; // 1
n = 1 ^ 1; // 0


代码示例:

 public class Main {
  public static void main(String[] args) {
    int i = 11; // 00000000 00000000 00000000 00001011
    int n = 9; // 00000000 00000000 00000000 00001001
    System.out.println(i & n); // 9
   }
 }

 


 
posted @ 2020-01-17 15:17  小宏的菜地  阅读(2282)  评论(0编辑  收藏  举报