Represent MD5 hash as an integer

Viewed 51780

In my user database table, I take the MD5 hash of the email address of a user as the id.

Example: email(example@example.org) = id(d41d8cd98f00b204e9800998ecf8427e)

Unfortunately, I have to represent the ids as integer values now - in order to be able to use an API where the id can only be an integer.

Now I'm looking for a way to encode the id into an integer for sending an decode it again when receiving. How could I do this?

My ideas so far:

  1. convert_uuencode() and convert_uudecode() for the MD5 hash
  2. replace every character of the MD5 hash by its ord() value

Which approach is better? Do you know even better ways to do this?

I hope you can help me. Thank you very much in advance!

8 Answers

A simple solution could use intval() by specifying base 16 as the second argument.

Systems that can accommodate 64-bit Ints can split the 128-bit/16-byte md5() hash into two 8-byte sections and then convert each. Each hex pair represents 1 byte, so use 16 character chunks in this case:

$hash = md5($value);
$inthash1 = intval(substr($hash, 0, 16), 16);
$inthash2 = intval(substr($hash, 16, 16), 16);

For 32-bit Ints, the hex chunks are 8 characters:

foreach (str_split($hash, 8) as $chunk) {
    $int_hashes[] = intval($chunk, 16);
}

what about:

$float = hexdec(md5('string'));

or

$int = (integer) (substr(hexdec(md5('string')),0,9)*100000000);

Definitely bigger chances for collision but still good enaugh to use instead of hash in DB though?

Related