Java怎样实现将Ip地址从int和String的相互转换

IP地址是32位(ipv4),刚好对应32位的int值public String ipInt2Str(int ip){ final StringBuilder sb = new StringBuilder() sb.append(String.valueOf(ip\u0026gt;\u0026gt;\u0026gt;24)).append("."); sb.append(String.valueOf((ip\u0026amp;0xFFFFFF)\u0026gt;\u0026gt;\u0026gt;16 )).append("."); sb.append(String.valueOf((ip\u0026amp;0xFFFF)\u0026gt;\u0026gt;\u0026gt;8 )).append("."); sb.append(String.valueOf(ip\u0026amp;0xFF)).append("."); return sb.toString();}public int ipStr2int(String ipstr){ final byte bytes = InetAddress.getByName(ipAddr).getAddress(); int addr = bytes \u0026amp; 0xFF; addr |= ((bytes \u0026lt;\u0026lt; 8) \u0026amp; 0xFF00); addr |= ((bytes \u0026lt;\u0026lt; 16) \u0026amp; 0xFF0000); addr |= ((bytes \u0026lt;\u0026lt; 24) \u0026amp; 0xFF000000) return addr;}或者byte ret = new byte;try { String ipArr = ipAddr.split("\\\\."); ret = (byte) (Integer.parseInt(ipArr) \u0026amp; 0xFF); ret = (byte) (Integer.parseInt(ipArr) \u0026amp; 0xFF); ret = (byte) (Integer.parseInt(ipArr) \u0026amp; 0xFF); ret = (byte) (Integer.parseInt(ipArr) \u0026amp; 0xFF); return ret; } catch (Exception e) { throw new IllegalArgumentException(ipAddr + " is invalid IP");}转换bytes数组
■网友
int 占用四个字节,可以对应ip地址,但是这里有个问题就是符号,需要考虑符号问题。下边是我的一个处理办法。调用实例String result = ipInt2Str((192 \u0026lt;\u0026lt; 24) + (168 \u0026lt;\u0026lt; 16) + (1 \u0026lt;\u0026lt; 8) + 1);public static String ipInt2Str(int ip) { int first = ip\u0026gt;\u0026gt;24; if(first\u0026lt;0){ first = 0xff+first+1; } int second = ip\u0026gt;\u0026gt;16 \u0026amp; 0xff; int third = ip\u0026gt;\u0026gt;8 \u0026amp; 0xff; int four = ip \u0026amp; 0xff; StringBuffer buf = new StringBuffer(); buf.append(first).append(".").append(second).append(".") .append(third).append(".").append(four).append("."); return buf.toString(); }


    推荐阅读