对于Java或Scala程序员来说,这有点蠢蠢欲动

Joh*_*nes 4 java bit-manipulation

有没有人知道好的教程,甚至是掌握位级操作的好书?我的意思是几乎清楚每个操作的作用(例如在Java中)或在哪里找到正确的文档,但我对这个主题很新,我想知道如何:

// Find a power of 2 >= initialCapacity
int capacity = 1;
while (capacity < initialCapacity)
    capacity <<= 1;
Run Code Online (Sandbox Code Playgroud)

工作(复制自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);
}
Run Code Online (Sandbox Code Playgroud)

这似乎是魔术:(

Mic*_*wan 6

要了解基础知识,您需要了解数据的表示方式.这需要理解二进制,通常是两个补码.

一旦你理解了基础知识,就可以在无处不在的斯坦福大学找到很多有用的黑客.