在網絡編程中,IP 地址常以 32 位長整型存儲以節省空間並提高比較效率。本文提供一個將 Long 類型轉換為標準點分十進制 IP 字符串的工具方法。
/**
* 將長整型解析為 IP 地址
* @param num 32 位長整型 IP
* @return 標準 IPv4 字符串
*/
public static String int2iP(Long num) {
if (num == null) return null;
long[] octets = new long[4];
octets[0] = (num >>> 24) & 0xFF;
octets[1] = (num >>> 16) & 0xFF;
octets[2] = (num >>> 8) & 0xFF;
octets[3] = num & 0xFF;
return String.format("%d.%d.%d.%d", octets[0], octets[1], octets[2], octets[3]);
}
>>>> 配合掩碼 0xFF 提取各字節原代碼中存在冗余移位操作(如 >>> 0),建議簡化為上述版本。同時增加空值檢查,增強健壯性。
BIGINT 或 INT UNSIGNED