/** * ClassName: Ip2Long<br/> * Description: ip和long互转<br/> * date: 2019/4/16 5:53 PM<br/> * * @author chengluchao * @since JDK 1.8 */ public class Ip2Long { public static void main(String[] args) { System.out.println(ipToLong("78.23.0.142")); System.out.println(longToIP(ipToLong("1.2.3.4"))); } public static long ipToLong(String ip) { ip = ip.replaceAll(" ", ""); String[] ipArray = ip.split("\."); long ipLong = (Long.parseLong(ipArray[0]) << 24) + (Long.parseLong(ipArray[1]) << 16) + (Long.parseLong(ipArray[2]) << 8) + Long.parseLong(ipArray[3]); return ipLong; } public static String longToIP(long ip) { long a = ip % 256; long b = (ip -= a) >> 24; long c = (ip -= b << 24) >> 16; long d = (ip -= c << 16) >> 8; StringBuffer sb = new StringBuffer(); sb.append(b); sb.append("."); sb.append(c); sb.append("."); sb.append(d); sb.append("."); sb.append(a); return sb.toString(); } }