在下面的示例代碼中,有人可以通過更詳細地解釋下面的行究竟在做什麼,就像你會向開發人員解釋它一樣。此Java代碼如何工作以轉換IP地址?
for (byte octet : octets) {
result <<= 8;
result |= octet & 0xff;
}
public class Example {
public static long ipToLong(InetAddress ip) {
byte[] octets = ip.getAddress();
long result = 0;
for (byte octet : octets) {
result <<= 8;
result |= octet & 0xff;
}
return result;
}
public static void main(String[] args) throws UnknownHostException {
long ipLo = ipToLong(InetAddress.getByName("192.200.0.0"));
long ipHi = ipToLong(InetAddress.getByName("192.255.0.0"));
long ipToTest = ipToLong(InetAddress.getByName("192.200.3.0"));
System.out.println(ipToTest >= ipLo && ipToTest <= ipHi);
}
}
替換'new BigInteger(ip.getAddress())。longValue()'。 – jtahlborn 2012-07-18 20:16:59