Java的位元運算符筆記,Java運算子筆記

來源:互聯網
上載者:User

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;       //11000000000000000000000000000000System.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

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.