Hashes a 32-bit signed int - CSharp System

CSharp examples for System:Int32

Description

Hashes a 32-bit signed int

Demo Code


using System.Collections;
using System;/*from ww  w  .  j  av  a  2  s  .  com*/

public class Main{
        /// <summary>
      /// Hashes a 32-bit signed int using Thomas Wang's method v3.1 (http://www.concentric.net/~Ttwang/tech/inthash.htm).
      /// Runtime is suggested to be 11 cycles. 
      /// </summary>
      /// <param name="input">The integer to hash.</param>
      /// <returns>The hashed result.</returns>
      private static int HashInt32(T input)
      {
         var x = input as uint?;
         unchecked
         {
            x = ~x + (x << 15); // x = (x << 15) - x- 1, as (~x) + y is equivalent to y - x - 1 in two's complement representation
            x = x ^ (x >> 12);
            x = x + (x << 2);
            x = x ^ (x >> 4);
            x = x * 2057; // x = (x + (x << 3)) + (x<< 11);
            x = x ^ (x >> 16);
            return (int)x;
         }
      }
}

Related Tutorials