解決PHP函數ip2long轉換IP時數值太大而產生負數的辦法

【造成原因】:Because PHP's integer type is signed, and many IP addresses will result in negative integers.

【解決辦法】:其官方手冊中提到,可以“you need to use the "%u" formatter of sprintf() or printf() to get the string representation of the unsigned IP address”

即,printf( '%u', ip2long( 'IP地址' ) );

或者將其先轉換爲二進制然後在轉換爲十進制,bindec( decbin( ip2long( 'IP地址' ) ) );

【測試】

$strIp = '182.118.0.0';

echo ip2long($strIp); //此時輸出的-1233780736

echo '<br/>';

echo bindecdecbinip2long( $strIp ) ) ); // 輸出3061186560,與MySQL函數輸出一致~


【注】:

number bindec ( string $binary_string ); //二進制轉換爲十進制

string decbin ( int $number ); //十進制轉換爲二進制
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章