Java编程IP地址和数字相互转换代码示例
最近才知道,将ip地址转换成十进制、八进制、十六进制同样可以访问网站。
IP转为数字(第二种算法。用左移、按位或实现。效率更高。):
public long ipToLong(String ipAddress) { long result = 0; String[] ipAddressInArray = ipAddress.split("\\."); for (int i = 3; i >= 0; i--) { long ip = Long.parseLong(ipAddressInArray[3 - i]); //left shifting 24,16,8,0 and bitwise OR //1. 192 << 24 //1. 168 << 16 //1. 1 << 8 //1. 2 << 0 result |= ip << (i * 8); } return result; }
数字转为IP,两种算法都差不多:
//ip = 3232235778 public String longToIp(long ip) { StringBuilder result = new StringBuilder(15); for (int i = 0; i < 4; i++) { result.insert(0,Long.toString(ip & 0xff)); if (i < 3) { result.insert(0,'.'); } ip = ip >> 8; }SYCXPj return result.toString(); } //ip = 3232235778 public String longToIp2(long ip) { return ((ip >> 24) & 0xFF) + "." 开发者_JS学习 + ((ip >> 16) & 0xFF) + "." + ((ip >> 8) & 0xFF) + "." + (ip & 0xFF); }
完整代码:
public class javaBitwiseExample { public static void main(String[] args) { JavaBitwiseExample obj = new JavaBitwiseExample(); System.out.println(SYCXPj"iptoLong : " + obj.ipToLong("192.168.1.2")); System.out.println("iptoLong2 : " + obj.ipToLong2("192.168.1.2")); System.out.println("longToIp : " + obj.longToIp(3232235778L)); System.out.println("longToIp2 : " + obj.longToIp2(3232235778L)); } // example : 192.168.1.2 public long ipToLong(String ipAddress) { // ipAddressInArray[0] = 192 String[] ipAddressInArray = ipAddress.split("\\."); long result = 0; for (int i = 0; i < ipAddressInArray.length; i++) { int power = 3 - i; int ip = Integer.parseInt(ipAddressInArray[i]); // 1. 192 * 256^3 // 2. 168 * 256^2 // 3. 1 * 256^1 // 4. 2 * 256^0 result += ip * Math.pow(256, power); SYCXPj } retuwww.devze.comrn result; } public long ipToLong2(String ipAddress) { long result = 0; String[] ipAddressInArray = ipAddress.split("\\."); for (int i = 3; i >= 0; i--) { long ip = Long.parseLong(ipAddressInArray[3 - i]); // left shifting 24,16,8,0 and bitwise OR // 1. 192 << 24 // 1. 168 << 16 // 1. 1 << 8 // 1. 2 << 0 result |= ip << (i * 8); } return result; } public String longToIp(long i) { return ((i >> 24) & 0xFF) + "." + ((i >> 16) & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + (i & 0xFF); } public String longToIp2(long ip) { Strinhttp://www.devze.comgBuilder sb = new StringBuilder(15); for (int i = 0; i < 4; i++) { // 1. 2 // 2. 1 // 3. 168 // 4. 192 sb.insert(0, Long.toString(ip & 0xff)); if (i < 3) { sb.insert(0, '.'); } // 1. 192.168.1.2 // 2. 192.168.1 // 3. 192.168 // 4. 192 ip = ip >> 8; } return sb.toString(); } }
总结
以上就是本文关于Java编程IP地址和数字相互转换代码示例的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出!
精彩评论