In the example code below could someone walk through a more detailed explanation of exactly what the lines below are actually doing like you’d explain it to a beginning developer.
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);
}
}
byte[] octets = ip.getAddress();-> stores entire IP address as byte arrayfor (byte octet : octets) {}-> splits the byte-array into octets and iterates over themresult <<= 8 (shorthand for result = result<<8)-> Left-shift 8 bits shifts the result in binary by 8 bits, and adds 8 trailing zeros. (Multiplies the value of result by 2^8)result |= octet & 0xff; (same as result|=octet which is shorthand for result = result | or octect-> Bitwise ORing, same as addition in this case, because we have 8 zeros at the end ofresult, after the previous step.EDIT (thanks to @jtahlborn) -> the bitwise-anding with 0xFF is necessary to avoid sign extension when the byte is converted to an int.
Example
192.200.3.0is the IP address in question. The final value isThis is generated in the following manner
Now your code does the same, but using bitwise shifts
192 in binary is
11000000. First, it is added to result = 0;result is now
11000000.Then it is shifted left by 8 bits (effectively multiplying it by 2^8)
result is
11000000 00000000Now, binary value of 200, which is
11001000is added, making result now11000000 11001000This process is carried on, till you have the following 32 bit number,
11000000 11001000 00000011 00000000which translates to the same 3234333440