1. 程式人生 > 其它 >Java位運算

Java位運算

位運算

>>> 無符號右移,第一位符號位不變,其他位用0補齊
>> 右移,整體右移,左邊的用0補齊
<< 左移,整體左移,右邊的用0補齊
| 或:有1則1
& 與:有0則0
^ 異或:相反為1,否則為0
~ 取反:

寫個測試

1.5以後的jdk中,Integer等數字型別內部維護了一個成員變數叫 SIZE,以Integer為例:

/**
 * The number of bits used to represent an {@code int} value in two's
 * complement binary form.
 *
 * @since 1.5
 */
@Native public static final int SIZE = 32;

可以看出,Integer的長度是32位。下面是測試程式碼:

/**
 * 列印int資料的二進位制
 *
 * @param num int
 */
private static void printBit(int num) {
for (int i = 31; i >= 0; i--) {
int i1 = num & (1 << i); // 1 左移 i 位,和num進行一個&與運算,如果結果是0,則列印0,否則列印1
        System.out.print(i1 == 0 ? "0" : "1");
    }
System.out.println("");
}

下面開始位運算:

public class BitOperationTest {

    /**
     * 列印int資料的二進位制
     *
     * @param num int
     */
private static void printBit(int num) {
for (int i = 31; i >= 0; i--) {
int i1 = num & (1 << i); // 1 左移 i 位,和num進行一個&與運算,如果結果是0,則列印0,否則列印1
            System.out.print(i1 == 0 ? "0" : "1");
        }
System.out.println("");
    }

public static void main(String[] args) {
        int i = 10;
        System.out.println("i : 10");
        printBit(i);
        int leftMove = i << 3;
        System.out.println("leftMove : ");
        printBit(leftMove);
        int rightMove = i >> 3;
        System.out.println("rightMove : ");
        printBit(rightMove);
        int unsignRightMove = i >>> 3;
        System.out.println("unsignRightMove : ");
        printBit(unsignRightMove);

        System.out.println("===========");
        System.out.println("i : 10");
        printBit(i);
        int j = -10;
        System.out.println("j : -10");
        printBit(j);

        int or = i | j;
        System.out.println(" i | j : ");
        printBit(or);
        int and = i & j;
        System.out.println("i & j : ");
        printBit(and);
        int xor = i ^ j;
        System.out.println(" i ^ j : ");
        printBit(xor);

        int neg = ~ i;
        System.out.println(" ~ i : ");
        printBit(neg);
    }
}

執行結果如下:

反碼、補碼

在上圖可以看出,-10的二進位制是 11111111111111111111111111110110,這裡做個解釋。

第一位是符號位,0表示正數,1表示負數。先對這個二進位制數取反,得到 00000000000000000000000000001001,這就是反碼 ,然後在反碼的基礎上+1,得到 補碼00000000000000000000000000001010,這個數就是二進位制的10,然後加上符號位,即-10。

Java各基礎資料長度

看下Integer中的程式碼:

/**
 * The number of bits used to represent an {@code int} value in two's
 * complement binary form.
 *
 * @since 1.5
 */
@Native public static final int SIZE = 32;

/**
 * The number of bytes used to represent a {@code int} value in two's
 * complement binary form.
 *
 * @since 1.8
 */
public static final int BYTES = SIZE / Byte.SIZE;

可知Integer的二進位制長度為32位,有四個位元組。

型別 二進位制長度 位元組數 範圍
byte 8 2 -128~127
short 16 4 -32768~32767
int 32 8 -2^31 ~ 2^31-1
long 64 16 -263~263-1
char 16 4 0~65535

程式碼地址