Mega Code Archive

 
Categories / Java / Development Class
 

Paul Hsiehs Hash Function

/*  * To change this template, choose Tools | Templates  * and open the template in the editor.  */ //package org.ancora.SharedLibrary; /**  * Methods for bit manipulation.  *  * @author Joao Bispo  */ public class Util{   private static final long MASK_16_BITS = 0xFFFFL;      private static final int MASK_BIT_1 = 0x1;      /**       * Paul Hsieh's Hash Function.       *       * @param data data to hash       * @param dataLength length of the data, in bytes       * @param hashedValue previous value of the hash. If it is the start of the       * method, used the length of the data (ex.: 8 bytes).       * @return       */      public static int superFastHash(long data, int hash) {         int tmp;         //int rem;         //if (len <= 0) {         //   return 0;         //}         //rem = len & 3;         //len >>= 2;         //Main Loop         for (int i = 0; i < 4; i += 2) {            // Get lower 16 bits            hash += get16BitsAligned(data, i);            // Calculate some random value with second-lower 16 bits            tmp = (get16BitsAligned(data, i + 1) << 11) ^ hash;            hash = (hash << 16) ^ tmp;            // At this point, it would advance the data, but since it is restricted            // to longs (64-bit values), it is unnecessary).            hash += hash >> 11;         }         // Handle end cases //         // There are no end cases, main loop is done in chuncks of 32 bits.         // Force "avalanching" of final 127 bits //         hash ^= hash << 3;         hash += hash >> 5;         hash ^= hash << 4;         hash += hash >> 17;         hash ^= hash << 25;         hash += hash >> 6;         return hash;      }      /**       * Returns 16 bits from the long number.       *        * @param data       * @param offset one of 0 to 3       * @return       */      public static int get16BitsAligned(long data, int offset) {         // Normalize offset         offset = offset%4;         //System.out.println("offset:"+offset);         // Align the mask         long mask = MASK_16_BITS << 16*offset;         //System.out.println("Mask:"+Long.toHexString(mask));         //System.out.println("Data:"+Long.toHexString(data));         // Get the bits         long result = data & mask;         // Put bits in position         return (int) (result >>> (16*offset));      } }