Represent MD5 hash as an integer

前端 未结 8 2140
Happy的楠姐
Happy的楠姐 2021-02-05 09:42

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)

8条回答
  •  遇见更好的自我
    2021-02-05 10:12

    For a 32-bit condensation, a simple solution could be made by selecting 4 hex pairs (8 characters) of the MD5 hash, where each pair represents one byte, and then converting that with intval().

    For an unsigned 32-bit Int:

    $inthash = intval(substr(md5($str), 0, 8), 16);
    

    For the positive value only of a signed 32-bit Int:

    $inthash = intval(substr(md5($str), 0, 8), 16) >> 1;
    

    This will likely only work for values up to 64-bit (8 bytes or 16 characters) for most modern systems as noted in the docs.

    On a system that can accommodate 64-bit Ints, a splitting strategy that consumes the entire 128-bit MD5 hash as 2 Ints might look like:

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

提交回复
热议问题