2012-11-16 25 views
4

我在PHP中創建了一個crc32,並且需要將它存儲在MySQL數據庫的一個字段中。在閱讀了關於如何關注32位和64位機器的結果後,我想知道如何存儲這個數字。這是我如何處理PHP中的CRC32得到任何bitsize機上相同的結果:如何在MySQL中存儲crc32?

<?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 . "\n"; 
printf("%u\n", $checksum); 
$string = sprintf("%u", $checksum); 
echo $string . "\n"; 
?> 

輸出(在64位機器上):

checksum without printf formatting: 2191738434 
2191738434 
2191738434 

如何把這個號碼存儲在MySQL?下面是我想出來的,到目前爲止幾個選擇:

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

它看起來像我應該去:

`hash4` BIGINT UNSIGNED NOT NULL , 
+1

只需使用一個64位無符號場(UNSIGNED BIGINT)。 –

回答

4

你可以在MySQL中的值存儲爲INT UNSIGNED佔據4個字節(即32位)。

要值插入到數據庫中,你必須在32臺機器上使用sprintf()%u格式:

$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), 
)); 

更新

你也可以確保你總是有工作32位和64位平臺上的int32類型(長符號)。目前,您只能通過pack()unpack()做到這一點:

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

這樣做的想法貢獻的mindplay.dk

+0

需要警告的是,從表中加載散列值會導致它重新回到一個有符號的整數 - 在經歷了一次大的失敗(以及之後的大量拖拽)之後,我[強烈推薦](http://us2.php。 net/manual/en/function.crc32.php#113079)堅持有符號整數,在32和64位平臺上表現相同。嘗試'解壓('l',pack('l',crc32(...)))'這是我能找到的最簡單的方法,以保證便攜式結果。 –

+0

@ mindplay.dk這取決於你如何檢索它,因爲大多數數據庫層將它作爲字符串值返回;話說回來,需要一個一致的int32值得我的回答更新:) –

+0

一些現代的DB層將'INTEGER'列輸入到實際的整數,這樣你就可以用嚴格的'===比較。感謝您在更新中爲我帶來這個想法:-) –