首页 > 解决方案 > 为什么 Java BitSet 被打包成 6 个字节?

问题描述

我正在研究BitSet,但我不清楚以下几点:

  1. 当我们传递位数时,除以6。为什么6正在使用而不是 2 的某个幂?
  2. 在初始化底层数组时,为什么在除法之前先减 1,6然后加 1?

标签: javaperformancebytebitset

解决方案


我假设您正在询问 JDK 中的这段代码:

private static int wordIndex(int bitIndex) {
    return bitIndex >> ADDRESS_BITS_PER_WORD; // ADDRESS_BITS_PER_WORD is 6, question 1
}

public BitSet(int nbits) {
    // nbits can't be negative; size 0 is OK
    if (nbits < 0)
        throw new NegativeArraySizeException("nbits < 0: " + nbits);

    initWords(nbits);
    sizeIsSticky = true;
}

private void initWords(int nbits) {
    words = new long[wordIndex(nbits-1) + 1]; // question 2
}

initWords初始化 along[]以支持位,本质上将位存储到 64 位的“字”中。请注意,这似乎是一个实现细节。这应该多长时间long[]?好吧,它应该是最后一个单词的单词索引+ 1,因为索引是从零开始的。

最后一个词的索引是多少?好吧,该wordIndex方法可以告诉我们一个的单词索引,所以如果我们给它最后一位的索引,nbits - 1(同样因为索引是从零开始的),它会给我们想要的。这应该回答你的第二个问题。

如何wordIndex找到单词索引?嗯,a 中有 64 位long,所以我们只需要将 a 除以bitIndex64。除以 64 的另一种方法是什么?左移 6 次,因为 64 = 2 的 6 次方。有关更多信息,请参阅此帖子


推荐阅读