这个Java代码如何转换ip地址?

这个Java代码如何转换ip地址?,java,Java,在下面的示例代码中,是否有人能够像您向刚开始开发的开发人员解释的那样,详细解释下面几行代码的实际用途 for (byte octet : octets) { result <<= 8; result |= octet & 0xff; } public class Example { public static long ipToLong(InetAddress ip) { byte[] octets = ip.getAdd

在下面的示例代码中,是否有人能够像您向刚开始开发的开发人员解释的那样,详细解释下面几行代码的实际用途

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);
}
for(字节八位组:八位组){
结果
  • byte[]octets=ip.getAddress();
    ->将整个ip地址存储为字节数组

  • for(byte-octet:octets){}
    ->将字节数组拆分为八位字节并对其进行迭代


  • result替换为
    new BigInteger(ip.getAddress()).longValue()
    。当字节转换为int时,0xFF是避免符号扩展所必需的。我忘了这一点!太棒了!@jtahlborn Nice!甚至没有想到这一点谢谢,Nice write up将接受答案…但它为什么会这样做?“左移位8位将二进制结果移位8位,并添加8个尾随零。(将结果值乘以2^8)”,您能进一步解释一下吗?谢谢!
    192*(2^24) + 200*(2^16) + 3*(2^8) + 0*(2^0)
    3221225472 + 13107200 + 768 = 3234333440