I have a question about Guava's InetAddress.coerceToInteger method.
According to docs the method:
public static int coerceToInteger(InetAddress ip)
'Returns an integer representing an IPv4 address regardless of whether the supplied argument is an IPv4 address or not. '
But, IPv4 range is of an unsigned 32 bit while Java's int is a signed one - means the returned value can only cover half of the relevant range of IPv4.
Am I missing someone or there is a real problem in the method?
Thanks
A 32-bit value is a 32-bit value and it can have 2^32 values whether it is signed or unsigned. If you have an address like 192.168.0.1 it will be a negative number, no information is lost. If you turn this into bytes (which are also signed) no information is lost.
BTW: For IPv4 addresses you can use this trick
int address = ip.hashCode();
To treat a 32-bit signed value as a 32-bit unsigned value you can
int address32 = ...
long address = address32 & 0xFFFFFFFFL;
However, you shouldn't need to do this in most situations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With