Home » Php » sql – How to convert PHP's crc32 hash into the MySQL equivalent?

sql – How to convert PHP's crc32 hash into the MySQL equivalent?

Posted by: admin July 12, 2020 Leave a comment

Questions:

Apparently MySQL’s CRC32() function returns an unsigned BIGINT, while PHP returns hexadecimal value.

In PHP:

hash('crc32','hello world') == 7813f744

In MySQL:

SELECT CRC32('hello world') == 222957957

The PHP CRC32 value is stored in a CHAR(8) column.

I can’t figure out how to turn the PHP generated hash into the same value that MySQL produces only using SQL. The obvious doesn’t seem to work:

SELECT HEX(CRC32('hello world')) == D4A1185

SELECT CONV('7813f744',16,10) == 2014574404

Any ideas?

How to&Answers:

If you have 64-bit platform you can safely use crc32 function in PHP and CRC32 in MySQL. Quick test:

  php > echo crc32('foobar') . "\n";
  2666930069

MySQL:

  >select crc32('foobar');
  +-----------------+
  | crc32('foobar') |
  +-----------------+
  |      2666930069 |
  +-----------------+
  1 row in set (0.00 sec)

Answer:

It is possible to use the wrapper function that returns the same value as in mysql:

function mysql_compatible_crc32($s) {
    $r = crc32($s);
    if($r<0) {
        return 4294967296+$r;
    }
    return $r;
}