写一个安卓ipv4字符串,int值互相转换的函数
时间: 2024-02-25 20:51:28 浏览: 61
Android NDK中字符串的相互转换
5星 · 资源好评率100%
下面是一个可用的 Java 函数示例,可以实现 IPv4 字符串和 int 值之间的相互转换:
```java
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
public class IPv4Converter {
public static int ipv4ToInt(String ipv4) throws UnknownHostException {
InetAddress inetAddress = InetAddress.getByName(ipv4);
byte[] bytes = inetAddress.getAddress();
return ByteBuffer.wrap(bytes).getInt();
}
public static String intToIpv4(int ipv4Int) throws UnknownHostException {
byte[] bytes = ByteBuffer.allocate(Integer.SIZE / 8).putInt(ipv4Int).array();
InetAddress inetAddress = InetAddress.getByAddress(bytes);
return inetAddress.getHostAddress();
}
}
```
使用示例:
```java
String ipv4 = "192.168.0.1";
int ipv4Int = IPv4Converter.ipv4ToInt(ipv4);
System.out.println("IPv4 to int: " + ipv4Int);
System.out.println("Int to IPv4: " + IPv4Converter.intToIpv4(ipv4Int));
```
阅读全文