ipv4ToInt

This commit is contained in:
冉文杰
2025-06-13 14:51:07 +08:00
parent ae3a9ca588
commit aeafd4cb5d
2 changed files with 57 additions and 3 deletions
+56 -2
View File
@@ -18,12 +18,66 @@
思路: 思路:
``` 1. IPv4 地址由 4 个字节组成(如 192.168.1.1)
int toInt(){ 2. 每个字节对应整数的 8 位
3. 转换公式:(first << 24) | (second << 16) | (third << 8) | fourth
4. 使用位运算高效组合各部分
```C
unsigned ipv4_to_int(const char* ip){
unsigned char bytes[4];
const char* start = ip;
// 解析四个部分
for (int i = 0; i < 4; i++) {
// 查找下一个点或字符串结尾
const char* end = strchr(start, '.');
if (!end) end = start + strlen(start);
// 将当前部分转为整数
bytes[i] = (unsigned char)strtoul(start, NULL, 10);
// 移动到下一部分
start = end + 1;
}
// 组合四个字节
return (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3];
} }
``` ```
```Java
public class Ipv4Converter {
public static long ipv4ToInt(String ip) {
String[] parts = ip.split("\\.");
if (parts.length != 4) {
throw new IllegalArgumentException("Invalid IPv4 address format");
}
long result = 0;
for (int i = 0; i < 4; i++) {
int value = Integer.parseInt(parts[i]);
if (value < 0 || value > 255) {
throw new IllegalArgumentException("Invalid IP segment: " + value);
}
result = (result << 8) | value;
}
return result;
}
public static void main(String[] args) {
String ip = "192.168.1.1";
long result = ipv4ToInt(ip);
System.out.println("IPv4: " + ip);
System.out.println("Integer: " + result);
System.out.println("Hex: 0x" + Long.toHexString(result));
}
}
```
那么,int 转 ipv4 如何解呢? 那么,int 转 ipv4 如何解呢?
+1 -1
View File
@@ -8,7 +8,7 @@
* 把所有经典算法写一遍 * 把所有经典算法写一遍
* 看算法有关源码 * 看算法有关源码
* 加入算法学习社区,相互鼓励学习(加我vx:tiger-ran, 备注入群理由, 拉你入群) * 加入算法学习社区,相互鼓励学习
* 看经典书籍 * 看经典书籍
* 刷题 * 刷题