I开发者_如何转开发 have a issue the following:
- user_id(int(10))
oerder_type(tinyint(1))
convert from 1)+2) = int(11) to a hash
[0-9a-z]{8}
If you simply need a hash function for hash table lookup, I recommend using Murmurhash. 10^11 is between 2^36 and 2^37. Therefore, call a hash that generate 64-bit (Murmurhash2) or 128-bit (Murmurhash3) hash, and mod 10^11. Unlike simply converting bases, using hash function may generate conflicts, even it is highly (if not perfectly) uniformly distributed. However, you will get much better avalanche effect. Here is its avalanche test result.
If Murmurhash is not possible, Jenkins lookup functions are also good. Here is its avalanche test result.
If performance is not a problem, or it is required cryptographic secure, SHA-1 might be the best pick, which has much more wrappers in various languages. Do not use CRC32 (bad avalanche).
EDIT: If you need PHP hash function, here is a sample code
function my_hash($user_id, $order_type) { // construct integer (10^11) $data = $user_id * 10 + $order_type; // convert decimal to raw binary string (at most 5 bytes) $hex = dechex($data); $binary = pack('H*', $hex); // hash binary string. Substitute 'sha1' with other algorithms listed in http://www.php.net/manual/en/function.hash-algos.php if needed $hash = hash('sha1', $binary); // output first 8 bytes return substr($hash, 0, 8); } echo my_hash(1234567890, 0); // 199f4bc7 echo my_hash(1234567890, 1); // f3706f03
Also, there is PHP extension for Murmurhash2. You can compile and install if you run PHP on Linux. Replace those Murmurhash2 files with Murmurhash3 might be even better.
You can use a trivial hash function because:
36^8 = 2821109907456
10^12 - 1 = 999999999999
The range of [0-9a-z]{8}
is larger than 10^12 - 1
. The trivial hash function would be to convert your number from base 10 to base 36 and left padd with 0 to the required length.
As it was pointed out, this might not satisfy uniformity. However for a hash function uniformity is usually required to minimize the cost of collisions which do not exist in this case.
If that doesn't satisfy your requirements then you need to get more specific.
精彩评论