从127.0.0.1到2130706433,然后再回来 [英] Going from 127.0.0.1 to 2130706433, and back again
本文介绍了从127.0.0.1到2130706433,然后再回来的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用标准Java库,从IPV4地址(127.0.0.1
)的虚线字符串表示到等效整数的最快方法是什么?表示( 2130706433
)。
Using the standard Java libraries, what is the quickest way to get from the dotted string representation of an IPV4-address ("127.0.0.1"
) to the equivalent integer representation (2130706433
).
相应地,反转所述操作的最快方法是什么 - 从整数开始 2130706433
到字符串表示127.0.0.1
?
And correspondingly, what is the quickest way to invert said operation - going from the integer 2130706433
to the string representation"127.0.0.1"
?
推荐答案
String to int:
String to 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());
Int to string:
Int to string:
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()
这篇关于从127.0.0.1到2130706433,然后再回来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文