Java tutorial
//package com.java2s; public class Main { /** * <p> * Calculates the bucket id the key should be placed in according to the * first n bits of the key where n is the power of 2 numBuckets is defined * as. F.e if 1024 buckets are defined the first 10 bits of the key will be * taken as the index for the actual bucket (2^10 = 1024, 2^9 = 512, ...) * </p> * * @param key * The 64bit key whose bucket index should be calculated * @param numBuckets * The total number of available buckets. This should be a power * of two (e.g. 2, 4, 8, 16, 32, ...) * @return The bucket index the key should be in */ public static int getBucketForKey(long key, final int numBuckets) { // test if numBuckets is a power of 2 int exponent = Math.getExponent(numBuckets); if (numBuckets != Math.pow(2, exponent)) throw new IllegalArgumentException("Number of buckets does not correspond to a power of 2!"); return (int) (key >> (64 - exponent)) + numBuckets / 2; } }