簡體   English   中英

BitSet 的 set 方法如何處理向左移位的位?

[英]How does BitSet's set method work with bits shifting to the left?

Java 的BitSet類有一個方法Set將單個位設置為 1 (=true)。 方法源碼如下:

public void set(int bitIndex) {
    if (bitIndex < 0)
        throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex);

    int wordIndex = wordIndex(bitIndex);
    expandTo(wordIndex);

    words[wordIndex] |= (1L << bitIndex); // Restores invariants

    checkInvariants();
}

除了檢查之外,該方法的核心代碼是: words[wordIndex] |= (1L << bitIndex) 我可以在作業中清楚地看到左側部分是包含相關位的特定單詞。 但是,我不明白右側部分(位索引的左移)如何導致請求的(並且只有它)位設置為 1。您能解釋一下嗎?

1L << bitIndex產生一個long ,其位都是 0,除了其中一個位。 “1”位的位置由bitIndex確定。 例如,如果bitIndex為 10,則第 11 個最低有效位為 1。

0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0100 0000 0000

因為 1 向左移動了 10 次。 通常,第 ( bitIndex mod 64 + 1) 最低有效位是“1”位。

然后將此掩碼words[wordIndex]中的任何內容進行按位或運算。 words[wordIndex]中的每一位都保持不變,因為它們與 0 進行或運算,除了掩碼中它是“1”的地方。 由於 OR 的工作方式, words[wordIndex]中的那個位無論最初是什么都將變為“1”。

有兩個感興趣的部分: 1L << bitIndexwords[wordIndex] |=

第一部分1L << bitIndex移動了一些點。 這是一張表格,顯示了在幾個不同的換檔次數下它是如何發揮作用的。

陳述 十進制 二進制
1升 << 0 1 1
1L << 1 2 10
1L << 2 4 100
1L << 3 8 1000
1L << 4 16 10000

第二部分 – words[wordIndex] |= – 獲取words[wordIndex]中已有的任何值,並使用按位“或”來包含從上面隔離的任何位。 如果該位已設置(對於該字),則此操作不會更改任何內容。 如果該位為 0,則“或”操作 ( |= ) 會將該位設置為 1。

請記住,左側正在與該位進行 ORed ( | ),而最右邊的位(或最低有效位 - LSB)是位0 OR運算符會將源中指定的一位設置為目標中的相同位,而其他位保持不變。 這里有些例子。

int bits = 1;
System.out.println(Integer.toBinaryString(bits));
bits |= 0b100_0000_0000; // set bit 10 to 1.
System.out.println(Integer.toBinaryString(bits));

印刷

1
10000000001
^
bit 10

或者這樣做


System.out.println(Integer.toBinaryString(bits));
bits = 1;
// or it can be done this way.
bits |=  1<<10;  // 10 is the bitIndex in bits to set so it is shifted 
                 // left to that position and the result is as before
System.out.println(Integer.toBinaryString(bits));

印刷

10000000001
^
bit 10

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM