Russ
Russ

Reputation:

Good numeric hashes

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!

Upvotes: 13

Views: 4186

Answers (4)

OIS
OIS

Reputation: 10033

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

Upvotes: 0

nik
nik

Reputation: 13450

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

A short list,

Upvotes: 1

hobbs
hobbs

Reputation: 239871

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.

Upvotes: 4

Alix Axel
Alix Axel

Reputation: 154543

Maybe this is good enough for you:

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

EDIT: Other similar alternative,

echo hash('adler32', $string);

Upvotes: 3

Related Questions