public class IpToLong { public static long ipToLong(String ip) { long result = 0; String[] numbers = (ip + ".0.0.0").split("\\."); for (int i = 0; i < 4; i++) { result = result << 8; result |= Long.parseLong(numbers[i]) & 0xFF; } return result; } public static String longToIp(long ip) { return (ip >> 24 & 0xFF) + "." + (ip >> 16 & 0xFF) + "." + (ip >> 8 & 0xFF) + "." + (ip & 0xFF); } public static void main(String[] args) { String[] testList = { "0.0.0.0", "255.255.255.255", "192.168.1.2" }; for (String ip : testList) { long ipNum = ipToLong(ip); System.out.printf( "%s | %s | %s\n", ip, longToIp(ipNum), ipNum ); } } }
Output:
0.0.0.0 | 0.0.0.0 | 0 255.255.255.255 | 255.255.255.255 | 4294967295 192.168.1.2 | 192.168.1.2 | 3232235778
沒有留言:
張貼留言
你好!歡迎你在我的 Blog 上留下你寶貴的意見。