tags:

views:

124

answers:

4

Hi,

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!

+1  A: 

Maybe this is good enough for you:

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

EDIT: Other similar alternative,

echo hash('adler32', $string);
Alix Axel
+2  A: 

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.

hobbs
Yes, But, truncating or folding the hash result will cause it to loose quality both in terms of security and distribution.
nik
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.
hobbs
A: 

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

A short list,

nik
A: 

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
OIS