ipv4ToInt
This commit is contained in:
@@ -18,12 +18,66 @@
|
||||
|
||||
思路:
|
||||
|
||||
```
|
||||
int toInt(){
|
||||
1. IPv4 地址由 4 个字节组成(如 192.168.1.1)
|
||||
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 如何解呢?
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user