有没有人知道一些好的教程或者一本好的书来掌握位级操作?我的意思是,对于每个操作(例如在Java中),几乎都清楚它们是什么或者在哪里可以找到正确的文档,但是我对这个主题非常陌生,而我想知道像以下这样的东西:
// Find a power of 2 >= initialCapacity
int capacity = 1;
while (capacity < initialCapacity)
capacity <<= 1;
工作(从HashMap
复制)。我无法想象整数、长整型或任何数据类型如何受到位运算的影响 :-(
我的意思是,我不想知道每种操作,只想知道对于Java或Scala高级程序员来说似乎是基本的,就像提供的示例一样。
另一个例子是:
/**
* Applies a supplemental hash function to a given hashCode, which
* defends against poor quality hash functions. This is critical
* because HashMap uses power-of-two length hash tables, that
* otherwise encounter collisions for hashCodes that do not differ
* in lower bits. Note: Null keys always map to hash 0, thus index 0.
*/
static int hash(int h) {
// This function ensures that hashCodes that differ only by
// constant multiples at each bit position have a bounded
// number of collisions (approximately 8 at default load factor).
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
只是看起来像魔法一样 :(
1 << (32 - Integer.numberOfLeadingZeros(initialCapacity - 1))
或者甚至initialCapacity>1?Integer.highestOneBit(initialCapacity-1)<<1:initialCapacity
。 - bestsss