How to convert string (IP numbers) to Integer in J

2019-01-19 02:57发布

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");

标签: java parsing
5条回答
祖国的老花朵
2楼-- · 2019-01-19 03:40

You can do it for an IP V4 adress as the parts are just the four bytes of the integer version.

Do this to convert an InetAdress to its integer representation :

int result = 0;  
for (byte b: inetAdress.getAddress())  
{  
    result = result << 8 | (b & 0xFF);  
}

Note that you shouldn't use 32 bits integers for IP addresses now, as we're entering the era of IPV6 addresses.

EDIT : to parse a string like "123.45.55.34" to something useful in java, you may use INetAddress.getByName(yourString)

查看更多
我想做一个坏孩纸
3楼-- · 2019-01-19 03:47

You need to realize that an IPv4 address in the form 123.45.55.34 is actually 4 three digit numbers representing each byte of the address. Parsing the entire string all at once won't work.

Others have mentioned using an InetAddress, but if all you have is a string representation of the IP you can't easily instantiate an InetAddress as far as I know.

What you can do is something like the following:

public static int parseIp(String address) {
    int result = 0;

    // iterate over each octet
    for(String part : address.split(Pattern.quote("."))) {
        // shift the previously parsed bits over by 1 byte
        result = result << 8;
        // set the low order bits to the current octet
        result |= Integer.parseInt(part);
    }
    return result;
}
查看更多
爷、活的狠高调
4楼-- · 2019-01-19 03:56

IPAddressUtil#textToNumericFormatV4 performs better than String#split to get bytes of ip, besides, it checks if the ip is valid

 public int intOfIpV4(String ip) {
        int result = 0;
        byte[] bytes = IPAddressUtil.textToNumericFormatV4(ip);
        if (bytes == null) {
            return result;
        }
        for (byte b : bytes) {
            result = result << 8 | (b & 0xFF);
        }
        return result;
    }
查看更多
乱世女痞
5楼-- · 2019-01-19 03:57

You're likely to want to do this:

// Parse IP parts into an int array
int[] ip = new int[4];
String[] parts = "123.45.55.34".split("\\.");

for (int i = 0; i < 4; i++) {
    ip[i] = Integer.parseInt(parts[i]);
}

Or this:

// Add the above IP parts into an int number representing your IP 
// in a 32-bit binary form
long ipNumbers = 0;
for (int i = 0; i < 4; i++) {
    ipNumbers += ip[i] << (24 - (8 * i));
}

Of course, as others have suggested, using InetAddress might be more appropriate than doing things yourself...

查看更多
叛逆
6楼-- · 2019-01-19 04:00
System.out.println(
        ByteBuffer.allocate(Integer.BYTES)
        .put(InetAddress.getByName("0.0.1.0").getAddress())
        .getInt(0));

Output:

256

查看更多
登录 后发表回答