你的位置:首页 > Java教程

[Java教程]Java的位运算符笔记


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; //000000000000000000000000000000012 int j = 2; //000000000000000000000000000000103 int n = i&j;//000000000000000000000000000000004 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; //00000000000000000000000000000001int j = 2; //00000000000000000000000000000010int n = i|j;//00000000000000000000000000000011Sys.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; //00000000000000000000000000000001int j = 2; //00000000000000000000000000000010int n = i^j;//00000000000000000000000000000011System.out.println(n);//3

 

4.  ~(非)

  把0变1

  把1变0

    例:000  111  010  101

      ----------------------------

      111  000  101  010

int i = 1; //00000000000000000000000000000001int j = ~i;//11111111111111111111111111111110System.out.println(j);//-2

 

5. <<(左移)

  x<<n

  把x向左边平移n位。跑马灯?

    

int i = 2147483647; //01111111111111111111111111111111int j = i<<1;   //111111111111111111111111111111110System.out.println(j);//-2

 6. >> (右移)

  x<<n

  把x向右边平移n位。如图:

  

int i = 2147483647;//01111111111111111111111111111111int j = i>>1;   //00111111111111111111111111111111int o = -2147483647;//10000000000000000000000000000001int k = o>>1;System.out.print(j);//1073741823System.out.print(k);//-1073741823int n = i>>32;   System.out.print(n);//2147483647 >>>、>>和<<,如果移动了大于该类型的最大位数,移动位数就会被取模。这里实际移动了32%32=0

 

7. >>> (逻辑右移)

  x>>>n

  将x向右平移n位。正负均补0。

  

 

  

int i=2147483647;//01111111111111111111111111111111int j=i>>>1;   //00111111111111111111111111111111int o=-2;    //11111111111111111111111111111110int k=o>>>1;   //01111111111111111111111111111111System.out.println(j);//1073741823System.out.println(k);//2147483647