I suppose you talk about the implementation of this class?
It says so in a comment in the source file:
/*
* BitSets are packed into arrays of "words." Currently a word is
* a long, which consists of 64 bits, requiring 6 address bits.
* The choice of word size is determined purely by performance concerns.
*/
So from a given bit number, the lower 6 bits are used for addressing a bit withing a 64 bit word, and the remaining bits are for addressing the word.
For the point 2, I suppose you talk about
wordIndex(nbits-1) + 1
which is
bitIndex >> ADDRESS_BITS_PER_WORD
- Suppose you want to initialize a BitSet with initially 0 entries. Then you need an array size of 0.
- Suppose you want to initialize a BitSet with initially 1 to 64 entries. Then you need an array size of 1.
- Suppose you want to initialize a BitSet with initially 65 to 128 entries. Then you need an array size of 2.
And so on.
This means, you map the original range (1-64, 65-128) to "one less" (0-63, 64-127), divide by 64 (0, 1) and increase the result again (1, 2) to get the number of needed words in the array.
To demonstrate both:
Suppose you want a BitSet with 128 entries. You initialize it and you get an array with 2 64 bit entries. Why?
That's because wach word can hold 64 bits, so in order to hold 128 bits, you need 2 array entries:
(128-1)/64 + 1 = 127/64 + 1 = 1 + 1 = 2. (Remember that integer divisions go towards the lower value.)
Now, you want to set the bis 5, 13 and 66.
Bit 5 and 13 are fine - you just set bits 5 and 13 in the word at index 0.
But what do you do with the 66? Each word has only 64 bits! (0..63)
Well, in this situation, you substract 64 for each step you make in the array. So you go to word at index 1 and for "compensation", you go from 66 to 2.
That's exactly what happens with these bit manipulations: from each of these bit indexes, the lower 6 bits are taken and used as bit address in the respective word.
5 = 0 000101 = 0/5
13 = 0 001101 = 0/13
66 = 1 000001 = 1/2
So
- 5 is set by setting bit 5 in the word 0.
- 13 is set by setting bit 13 in the word 0.
- 66 is set by setting bit 2 in the word 1.