hashing a small number to a random looking 64 bit integer

前端 未结 4 668
臣服心动
臣服心动 2021-01-12 16:54

I am looking for a hash-function which operates on a small integer (say in the range 0...1000) and outputs a 64 bit int.

The result-set should look like a random dis

相关标签:
4条回答
  • 2021-01-12 17:20

    I tested the 64-bit finalizer of MurmurHash3 (suggested by @aix and this SO post). This gives zero if the input is zero, so I increased the input parameter by 1 first:

    typedef unsigned long long uint64;
    
    inline uint64 fasthash(uint64 i)
    {
      i += 1ULL;
      i ^= i >> 33ULL;
      i *= 0xff51afd7ed558ccdULL;
      i ^= i >> 33ULL;
      i *= 0xc4ceb9fe1a85ec53ULL;
      i ^= i >> 33ULL;
      return i;
    }
    

    Here the input argument i is a small integer, for example an element of {0, 1, ..., 1000}. The output looks random:

    i       fasthash(i) decimal:    fasthash(i) hex:
    0       12994781566227106604    0xB456BCFC34C2CB2C
    1       4233148493373801447     0x3ABF2A20650683E7
    2       815575690806614222      0x0B5181C509F8D8CE
    3       5156626420896634997     0x47900468A8F01875
    ...     ...                     ...
    

    There is no linear correlation between subsequent elements of the series:

    fasthash autocorrelation

    The range of both axes is 0..2^64-1

    0 讨论(0)
  • 2021-01-12 17:27

    1,000 * 1,000 = 1,000,000. That fits well within an Int32.

    Subtract the low bound of your range, from the number. Square it, and use it as a direct subscript into some sort of bitmap.

    0 讨论(0)
  • 2021-01-12 17:34

    Why not use an existing hash function, such as MurmurHash3 with a 64-bit finalizer? According to the author, the function takes tens of CPU cycles per key on current Intel hardware.

    0 讨论(0)
  • 2021-01-12 17:37

    Given: input i in the range of 0 to 1,000.

    const MaxInt which is the maximum value that cna be contained in a 64 bit int. (you did not say if it is signed or unsigned; 2^64 = 18446744073709551616 )

    and a function rand() that returns a value between 0 and 1 (most languages have such a function)

    compute hashvalue = i * rand() * ( MaxInt / 1000 )

    0 讨论(0)
提交回复
热议问题