Java移位運算符 << >> >>>


簡述

Java有三種移位運算符,分別為:

  1. 左移運算符 <<
  2. 右移運算符 >>
  3. 無符號右移運算符 >>>

首先,移位運算符根據名字可知是使用二進制進行運算的。在Integer.java中,我們可以看到有兩個靜態常量,MIN_VALUEMAX_VALUE,這兩個常量控制了Integer的最小值和最大值,如下:

    /**
     * A constant holding the minimum value an {@code int} can
     * have, -2<sup>31</sup>.
     */
    @Native public static final int   MIN_VALUE = 0x80000000;

    /**
     * A constant holding the maximum value an {@code int} can
     * have, 2<sup>31</sup>-1.
     */
    @Native public static final int   MAX_VALUE = 0x7fffffff;

注釋上說明這兩個值得范圍:

MIN_VALUE(最小值) = -2^31 = -2,147,483,648‬
MAX_VALUE(最大值) = 2^31 = 2,147,483,647

在32位運算中,首位為1則代表負數,0則代表正數,如:

1000 0000 0000 0000 0000 0000 0000 0000 負數,該值等於MIN_VALUE
0111 1111 1111 1111 1111 1111 1111 1111 正數,該值等於MAX_VALUE

根據上述可知,Integer是32位運算的。


左移運算符 <<

使用 << 時,需要在低位進行補0,例子如下:

        int a = 3;
        System.out.println(Integer.toBinaryString(a));

        int b = a << 1;
        System.out.println(Integer.toBinaryString(b));
        System.out.println(b);

        System.out.println("----------------------------------------------");

        int c = -3;
        System.out.println(Integer.toBinaryString(c));

        int d = c << 1;
        System.out.println(Integer.toBinaryString(d));
        System.out.println(d);

輸入如下:

11
110
6
----------------------------------------------
11111111111111111111111111111101
11111111111111111111111111111010
-6

可以清楚的看到 3 << 1 時,在后面補0,得到 110 即等於6;


右移運算符 >>

右移運算符時,正數高位補0,負數高位補1。如:

        int a = 3;
        System.out.println(Integer.toBinaryString(a));

        int b1 = a >> 1;
        System.out.println(Integer.toBinaryString(b1));
        System.out.println(b1);

        System.out.println("----------------------------------------------");

        int c = -3;
        System.out.println(Integer.toBinaryString(c));

        int d = c >> 1;
        System.out.println(Integer.toBinaryString(d));
        System.out.println(d);

輸出如下:

11
1
1
----------------------------------------------
11111111111111111111111111111101
11111111111111111111111111111110
-2

無符號右移 >>>

在正數當中,>> 和 >>> 是一樣的。負數使用無符號右移時,則高位不進行補位。

        int c = -3;
        System.out.println(Integer.toBinaryString(c));

        int d = c >>> 1;
        System.out.println(Integer.toBinaryString(d));
        System.out.println(d);

輸出如下:

11111111111111111111111111111101
1111111111111111111111111111110
2147483646

總結

左移運算符 << : 需要在低位進行補0
右移運算符 >> : 正數高位補0,負數高位補1
無符號右移運算符 >>> :在正數當中,>> 和 >>> 是一樣的。負數使用無符號右移時,則高位不進行補位

個人博客網址: https://colablog.cn/

如果我的文章幫助到您,可以關注我的微信公眾號,第一時間分享文章給您

微信公眾號


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM