Home » Php » mysql – PHP hashing function that returns an integer (32bit int)

mysql – PHP hashing function that returns an integer (32bit int)

Posted by: admin July 12, 2020 Leave a comment


The goal is to store the hash on a mysql database, using INT (not BIGINT or MEDIUMINT).
md5('string', true) returns binary data, 16 bytes of hash. I thought i could grep the first 4 bytes and convert it to an INT(32bit/4bytes) integer, but i don’t know how to do it.

What do you suggest? Thanks.

How to&Answers:
ord($hash[0]) * 16777216 + ord($hash[1]) * 65536 + ord($hash[2]) * 256 + ord($hash[3]) ;


unpack("L", substr($hash,0,4));

But Filip Roséen’s solution is better.


Use crc32, it will return a 32bit int.

var_dump (crc32 ("hello world"));
var_dump (crc32 ("world hello"));



PHP: crc32 – Manual

Generates the cyclic redundancy checksum polynomial of 32-bit lengths
of the str. This is usually used to validate the integrity of data
being transmitted.

Because PHP’s integer type is signed, and many crc32 checksums will
result in negative integers, you need to use the “%u” formatter of
sprintf() or printf() to get the string representation of the unsigned
crc32 checksum.


Another alternative is to use a map to link your hash to integer, such as Redis.

L43F34FLK34FL3K4 ==> 1




Here is Daniel J. Bernstein hash that returns an 32bit integer.

function djb_hash($str) {
  for ($i = 0, $h = 5381, $len = strlen($str); $i < $len; $i++) {
    $h = (($h << 5) + $h + ord($str[$i])) & 0x7FFFFFFF;
  return $h;