使用标准Java库,从IPV4-address("127.0.0.1"
)的虚线字符串表示到等效整数表示(2130706433
)的最快方法是什么.
相应地,反转所述操作的最快方法是什么 - 从整数2130706433
到字符串表示"127.0.0.1"
?
Geo*_*edy 31
字符串到int:
int pack(byte[] bytes) {
int val = 0;
for (int i = 0; i < bytes.length; i++) {
val <<= 8;
val |= bytes[i] & 0xff;
}
return val;
}
pack(InetAddress.getByName(dottedString).getAddress());
Run Code Online (Sandbox Code Playgroud)
Int到字符串:
byte[] unpack(int bytes) {
return new byte[] {
(byte)((bytes >>> 24) & 0xff),
(byte)((bytes >>> 16) & 0xff),
(byte)((bytes >>> 8) & 0xff),
(byte)((bytes ) & 0xff)
};
}
InetAddress.getByAddress(unpack(packedBytes)).getHostAddress()
Run Code Online (Sandbox Code Playgroud)
Ido*_*Ido 28
您还可以使用Google Guava InetAddress类
String ip = "192.168.0.1";
InetAddress addr = InetAddresses.forString(ip);
// Convert to int
int address = InetAddresses.coerceToInteger(addr);
// Back to str
String addressStr = InetAddresses.fromInteger(address));
Run Code Online (Sandbox Code Playgroud)
Wil*_*del 10
我修改了原来的答案.在Sun的实现中InetAddress
,该hashCode
方法生成IPv4地址的整数表示,但正如评论者正确指出的那样,JavaDoc无法保证这一点.因此,我决定使用ByteBuffer
该类来计算IPv4地址的值.
import java.net.InetAddress;
import java.nio.ByteBuffer;
// ...
try {
// Convert from integer to an IPv4 address
InetAddress foo = InetAddress.getByName("2130706433");
String address = foo.getHostAddress();
System.out.println(address);
// Convert from an IPv4 address to an integer
InetAddress bar = InetAddress.getByName("127.0.0.1");
int value = ByteBuffer.wrap(bar.getAddress()).getInt();
System.out.println(value);
} catch (Exception e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
输出将是:
127.0.0.1
2130706433
Run Code Online (Sandbox Code Playgroud)
小智 6
如果您需要学习长手数学,您可以使用 Substr 来删除八位字节。将表示类别的第一个八位字节乘以 (256*256*256) 或 (2^24) 第二个乘以 (256*256) (2^16) 第三个乘以 (256) (2^8) 第四个乘以 1 或(2^0)
127 * (2^24) + 0 *(2^16) + 0 * (2^8) + 1 * (2^0) 2130706432 + 0 + 0 + 1 = 2130706433
归档时间: |
|
查看次数: |
27810 次 |
最近记录: |