13

I'm looking to hash a string but I need the output to be an integer so I can't do md5. Do people here have any favorite numeric hashes that they might want to enlighten me with. I'm using PHP.

Thanks!

2
  • Do you mean a "good" hash as in Good security or as in good key distribution? The first will usually give you the second, but at a comparatively high cost. Commented Aug 25, 2009 at 4:36
  • 23
    The following page has several implementations of general purpose hash functions that are efficient and exhibit minimal collisions: partow.net/programming/hashfunctions/index.html Commented Oct 31, 2010 at 23:15

4 Answers 4

4

The output of MD5 is a number, just as with pretty much every imaginable hash. It's just a number that's usually expressed in hex. Use any hash algorithm that's conveniently available to you, chop as many bits as you want off of the end, and treat those bits as a number. Any good hash will have its last (or first, or middle) n bits just as evenly distributed as the whole value.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, But, truncating or folding the hash result will cause it to loose quality both in terms of security and distribution.
If the hash is good (if it's a suitable approximation to an ideal hash), then when you truncate it it will remain equally well-distributed, and won't lose any security except what's due to the reduced keyspace.
3

Maybe this is good enough for you:

echo sprintf('%u', crc32($string)); 

EDIT: Other similar alternative,

echo hash('adler32', $string); 

Comments

1

I think there are some good hashing and PHP specific questions already on Stackoverflow.
Try a hashing+php search here.

A short list,

Comments

0

You can use base_convert to change hexadecimal into decimal number and vice versa. If you want to convert integers (as a string) to hex you are limited to 32 bit numbers or less I belive (PHP_INT_MAX).

php -r 'foreach (hash_algos() as $hash) { echo $hash, "\n", $a = hash($hash, "test"), "\n", $b = base_convert($a, 16, 10), "\n", $c = base_convert($b, 10, 16), "\n", ($c === $a ? "yes" : "no"), "\n\n"; }' > hashes.txt 

Of the available hashes I had, these are the ones I could convert between decimal and hex:

adler32 c1015d04 3238092036 c1015d04 yes crc32 accf8b33 2899282739 accf8b33 yes crc32b d87f7e0c 3632233996 d87f7e0c yes 

Comments