# Java IP to Long

將 IP 地址轉換為整數並將其存入資料庫可以提高一些效能，尤其是當你需要進行 IP 地址範圍查詢或排序時。這種轉換方法稱為 "IP 地址壓縮" 或 "IP 地址轉換"，可以幫助減少數據庫查詢的時間。\
以下簡單的步驟和建議：

**步驟 1：IP 地址轉換為整數**

要將 IP 地址轉換為整數，你可以使用以下算法：

1. 將 IP 地址分割成四個整數部分，例如 192.168.1.1 將分割為 \[192, 168, 1, 1]。
2. 每個部分都可以轉換為 8 位二進制數。
3. 然後將這四個 8 位二進制數串接在一起，形成一個 32 位的二進制數。
4. 最後，將這個 32 位的二進制數轉換為十進制整數。

以下是 Java 代碼示例，用於將 IP 地址轉換為整數：

<pre class="language-java"><code class="lang-java"><strong>// IP字串轉換成long
</strong><strong>public static Long ipStringToLong(String ipStr) {
</strong>    String[] ips = ipStr.split("\\.");
    Long ipNum = 0l;
    for (String ip : ips) {
        ipNum = ipNum &#x3C;&#x3C; 8;
        ipNum += Integer.parseInt(ip);
    }
    return ipNum;
}

// IP的long值轉換成字串
public static String ipNumberToString(Long ipNum) {
    long[] base = {0xff000000, 0x00ff0000, 0x0000ff00, 0x000000ff};
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i &#x3C; 4; i++) {
        sb.append((ipNum &#x26; base[i]) >> 8 * (3 - i));
        if (i != 3)
            sb.append(".");
    }
    return sb.toString();
}

public static void main(String[] args) {
    String ip = "172.20.160.120";
    Long ipNum = ipStringToLong(ip);
    System.out.println("ipNum >> " + ipNum);
    String ipStr = ipNumberToString(ipNum);
    System.out.println("ipStr >> " + ipStr);
    System.out.println("result >> " + ip.equals(ipStr));
}
</code></pre>

```
// console log
ipNum >> 2887032952
ipStr >> 172.20.160.120
result >> true
```

**步驟 2：將整數存入資料庫**

一旦你將 IP 地址轉換為整數，你可以將整數存入資料庫的相應欄位中。通常，你會使用整數類型（如無符號整數）來存儲 IP 地址。這樣做的好處是數字比字符串更容易比較和排序，並且在查詢方面更有效率。

**步驟 3：進行 IP 範圍查詢**

當你需要查詢 IP 地址範圍時，你只需將要查詢的 IP 地址轉換為整數，然後使用標準的 SQL 查詢操作。例如，要查找位於某個 IP 地址範圍內的所有記錄，你可以執行以下查詢：

```sql
SELECT * FROM your_table
WHERE ip_address >= start_ip_integer
AND ip_address <= end_ip_integer;
```

**注意事項：**

* 請確保在將 IP 地址轉換為整數時處理錯誤，並驗證 IP 地址的格式。
* 在資料庫中存儲 IP 地址時，使用適當的整數類型，例如 UNSIGNED INT。
* 始終儲存 IP 地址範圍的開始和結束整數，以便輕鬆進行範圍查詢。

<table data-header-hidden><thead><tr><th width="194.33333333333331"></th><th width="101"></th><th></th></tr></thead><tbody><tr><td>型態</td><td>空間需求</td><td>範圍</td></tr><tr><td>TINYINT[(M)]</td><td>1 byte</td><td>Signed: -128 to 127 (-2^7 to 2^7-1)<br>Unsigned: 0 to 255 (0 to 2^8-1)</td></tr><tr><td>SMALLINT[(M)]</td><td>2 bytes</td><td>Signed: -32768 to 32767 (-2^15 to 2^15-1)<br>Unsigned: 0 to 65535 (0 to 2^16-1)</td></tr><tr><td>MEDIUNINT[(M)]</td><td>3 bytes</td><td>Signed: -8388608 to 8388607 (-2^23 to 2^23-1)<br>Unsigned: 0 to 16777215 (0 to 2^24-1)</td></tr><tr><td>INT[(M)]<br>INTEGER[(M)]</td><td>4 bytes</td><td>Signed: -2147483648 to 2147483647 (-2^31 to 2^31-1)<br>Unsigned: 0 to 4294967295 (0 to 2^32-1)</td></tr></tbody></table>

這種方法可以提高 IP 地址查詢的效能，特別是當你需要處理大量 IP 地址記錄時。然而，請確保在代碼中適當地處理 IP 地址的轉換和驗證，以確保數據的一致性和安全性。

#### 參考網站

* Java位元運算說明( 說明很清楚，對於新手很有幫助 ) : [前往](https://juejin.cn/post/6844904025880526861)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://xu-min-chang.gitbook.io/caster-develop-note/java/java-ip-to-long.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
