To convert an IP address to a long
value in Java, you can use the InetAddress
class to parse the IP address as a byte
array, and then use bit shifting and bitwise OR operations to combine the bytes into a single long
value.
Here is an example of how you can convert an IP address to a long
value in Java:
String ipAddress = "192.168.0.1"; InetAddress inetAddress = InetAddress.getByName(ipAddress); byte[] bytes = inetAddress.getAddress(); long value = ((bytes[0] & 0xffL) << 24) | ((bytes[1] & 0xffL) << 16) | ((bytes[2] & 0xffL) << 8) | (bytes[3] & 0xffL);
In this example, we have a String
called ipAddress
that contains an IP address. We use the InetAddress.getByName
method to parse the IP address as an InetAddress
object, and then use the getAddress
method to get the address as a byte
array. We then use bit shifting and bitwise OR operations to combine the bytes into a single long
value, which we assign to a long
variable called value
.