Java 位元運算(移位、位與、或、異或、非)

來源:互聯網
上載者:User

標籤:

public class Test {    public static void main(String[] args) {        // 1、左移( << )        // 0000 0000 0000 0000 0000 0000 0000 0101 然後左移2位後,低位補0://        // 0000 0000 0000 0000 0000 0000 0001 0100 換算成10進位為20        System.out.println(5 << 2);// 運行結果是20         // 2、右移( >> ) 高位補符號位        // 0000 0000 0000 0000 0000 0000 0000 0101 然後右移2位,高位補0:        // 0000 0000 0000 0000 0000 0000 0000 0001        System.out.println(5 >> 2);// 運行結果是1         // 3、無符號右移( >>> ) 高位補0        // 例如 -5換算成二進位後為:0101 取反加1為1011        // 1111 1111 1111 1111 1111 1111 1111 1011        // 我們分別對5進行右移3位、 -5進行右移3位和無符號右移3位:        System.out.println(5 >> 3);// 結果是0        System.out.println(-5 >> 3);// 結果是-1        System.out.println(-5 >>> 3);// 結果是536870911         // 4、位與( & )        // 位與:第一個運算元的的第n位於第二個運算元的第n位如果都是1,那麼結果的第n為也為1,否則為0        System.out.println(5 & 3);// 結果為1        System.out.println(4 & 1);// 結果為0         // 5、位或( | )        // 第一個運算元的的第n位於第二個運算元的第n位 只要有一個是1,那麼結果的第n為也為1,否則為0        System.out.println(5 | 3);// 結果為7         // 6、位異或( ^ )        // 第一個運算元的的第n位於第二個運算元的第n位 相反,那麼結果的第n為也為1,否則為0         System.out.println(5 ^ 3);//結果為6          // 7、位非( ~ )        // 運算元的第n位為1,那麼結果的第n位為0,反之。        System.out.println(~5);// 結果為-6     } }

 

位元運算符包括: 與(&)、非(~)、或(|)、異或(^)
  &:當兩邊運算元的位同時為1時,結果為1,否則為0。如1100&1010=1000
  | :當兩邊運算元的位有一邊為1時,結果為1,否則為0。如1100|1010=1110
  ~:0變1,1變0
  ^:兩邊的位不同時,結果為1,否則為0.如1100^1010=0110

Java 位元運算(移位、位與、或、異或、非)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.