以前無心中看到的一個阿里的面試題,而後就花了點時間去解決。原理就是利用int類型佔用四個字節32位來存放ip地址的四段8位二進制數。java
public class IpTest { public static void main(String[] args) { String ip = "192.168.23.106"; int intIp = stringIpToIntIp(ip); System.out.println(intIp); System.out.println(intIpToStringIp(intIp)); } /** * string類型ip轉int類型ip */ public static int stringIpToIntIp(String ip) { String[] ips = ip.split("\\."); if (ips.length != 4) { throw new IllegalArgumentException("請傳入正確的ipv4地址"); } StringBuilder str = new StringBuilder(); for (String s : ips) { int i = Integer.parseInt(s); if (i > 255 || i < 0) { throw new IllegalArgumentException("請傳入正確的ipv4地址"); } String bs = Integer.toBinaryString(i); str.append(String.format("%8s", bs).replace(" ", "0")); } //二進制字符串轉10進制,由於Integer.parseInt對負數轉的問題,因此本身手寫了轉化的方法 int n = 0; for (int i = 0; i < str.length(); i++) { String a = str.substring(i, i + 1); n = n << 1; if (a.equals("1")) { n = n | 1; } } return n; } /** * int類型ip轉string類型ip */ public static String intIpToStringIp(int intIp) { String str = Integer.toBinaryString(intIp); StringBuilder strIp = new StringBuilder(); for (int i = 0; i < 4; i++) { int sIp = Integer.parseInt(str.substring(i * 8, (i + 1) * 8), 2); strIp.append(sIp).append("."); } return strIp.substring(0, strIp.length() - 1); } }