在開發分表存儲系統時,使用 crc32() 作為哈希算法將用戶數據分散到 512 張表中。本地 32 位 Windows 開發環境運行正常,但部署到 64 位 Linux 服務器後,發現數據查詢失敗——同一用戶名在不同架構下產生了不同的哈希值。
PHP 手冊明確說明:
Because PHP's integer type is signed many crc32 checksums will result in negative integers on 32bit platforms. On 64bit installations all crc32() results will be positive integers though.
關鍵差異在於:
| 平台 | PHP_INT_SIZE | PHP_INT_MAX | crc32() 返回值 |
|---|---|---|---|
| 32 位 | 4 字節 | 2,147,483,647 | 可能為負數(有符號整數溢出) |
| 64 位 | 8 字節 | 9,223,372,036,854,775,807 | 始終為正數(無溢出) |
function _getHash($username) {
$hash = crc32($username) % 512;
return $hash;
}
function _getTable($username) {
$hash = self::_getHash($username);
return 'user_' . $hash;
}
使用 sprintf('%u') 強制轉換為無符號整數字符串,再取模:
function _getHash($username) {
// sprintf('%u') 確保在 32/64 位系統上都返回無符號整數字符串
$hash = sprintf('%u', crc32($username)) % 512;
return (int)$hash;
}
PHP 5.1.2+ 提供的 hash() 函數支援指定算法,結果一致性更好:
function _getHash($username) {
// crc32b 為大端序,結果與標準 CRC32 一致
$hash = hexdec(hash('crc32b', $username)) % 512;
return $hash;
}
crc32 碰撞率較高,生產環境建議使用 md5、sha1 或 murmurhashPHP 的整數類型與平台綁定是歷史遺留特性。跨平台部署時,凡涉及位運算、哈希計算、二進制協議解析的代碼,務必進行平台無關性測試,並使用 sprintf('%u')、pack/unpack 或 hash() 等手段確保行為一致。