duanfenhui5511 2012-11-16 15:49
浏览 169

如何将crc32存储在MySQL中?

I'm creating a crc32 in PHP and need to store it in a field in a MySQL database. After reading about how there is a concern about the results on a 32-bit vs 64-bit machine, I'm wondering how this number should be stored. This is how I'm treating the crc32 in PHP to get the same result on either bitsize machine:

<?php
$checksum = crc32("The quick brown fox jumped over the lazy dog.");
// On a 32-bit system it prints -2103228862 instead of
// 2191738434 which is correct and what prints on a 64-bit system. 
// See the php.net manual page on crc32 for more information about
// 32-bit vs 64-bit.
echo "checksum without printf formatting: " . $checksum . "
";
printf("%u
", $checksum);
$string = sprintf("%u", $checksum);
echo $string . "
";
?>

Output (on a 64-bit machine is):

checksum without printf formatting: 2191738434
2191738434
2191738434

How should this number be stored on MySQL? Here are a few choices I've come up with so far:

`hash1` CHAR(10) NOT NULL ,
`hash2` varchar(32) NOT NULL,
`hash3` int unsigned NOT NULL,

It looks like I should go with:

`hash4` BIGINT UNSIGNED NOT NULL ,
  • 写回答

1条回答 默认 最新

  • doumei2023 2012-11-16 16:12
    关注

    You can store the values in MySQL as INT UNSIGNED which occupies 4 bytes (i.e. 32 bits).

    To insert the values into the database, you must use sprintf() with %u format on 32 bit machines:

    $hash = crc32("The quick brown fox jumped over the lazy dog.");
    
    $stmt = $db->prepare('INSERT INTO mytable VALUES (:hash)');
    $stmt->execute(array(
        ':hash' => sprintf('%u', $hash),
    ));
    

    Update

    You could also make sure that you're always working with int32 types (signed long) on both 32 and 64-bit platforms. Currently, you can only accomplish this by using pack() and unpack():

    echo current(unpack('l', pack('l', $hash)));
    // returns -2103228862 on both 32-bit and 64-bit platforms
    

    The idea for this was contributed by mindplay.dk

    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条