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

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


Use crc32, it will return a 32bit int.


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

output

int(222957957)int(1292159901)

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.


ord($hash[0]) * 16777216 + ord($hash[1]) * 65536 + ord($hash[2]) * 256 + ord($hash[3]) ;

Or:

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

But Filip Roséen's solution is better.


Even better than crc32 will be the php hash() function:

hash("crc32b", $str);

If integer is required:

intval(hash("crc32b", $str), 16);

Compared to the plain crc32(), it will not be affected by the the signed/unsigned integer inconsistency between 32-bit and 64-bit systems (see PHP docs for the details: crc32)