Example:
// using Integer.parseInt
int i = Integer.parseInt("123");
How would you do the same for?
// using Integer.parseInt
int i = Integer.parseInt("123.45.55.34");
The following constitutes a valid IPv4 address: A string in decimal-dot notation, consisting of four decimal integers in the inclusive range 0–255, separated by dots (e.g. 192.168. 0.1 ). Each integer represents an octet (byte) in the address.
One effective way to convert a string object into a numeral int is to use the stoi() function. This method is commonly used for newer versions of C++, with is being introduced with C++11. It takes as input a string value and returns as output the integer version of it.
The IPAddress Java library supports both IPv4 and IPv6 in a polymorphic manner. Disclaimer: I am the project manager of that library.
The following code works with both IPv4 and IPv6 addresses. Using your example IPv4 address:
IPAddress addr = new IPAddressString("123.45.55.34").getAddress();
BigInteger value = addr.getValue(); // 2066560802
If IPv4, you can just go straight to an int value:
if(addr.isIPv4()) {
int val = addr.toIPv4().intValue(); // 2066560802
}
System.out.println(
ByteBuffer.allocate(Integer.BYTES)
.put(InetAddress.getByName("0.0.1.0").getAddress())
.getInt(0));
Output:
256
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