java 实现IP进制转换,IP进制与十进制互相转换

请看代码:

/**
 * IP进制转换工具
 * 
 * @author YM
 */
public class IpConvert {

	/**
	 * 将IP进制(如:192.168.1.1)转换成十进制(如:3232235777)
	 * 
	 * @param ip
	 * @return
	 */
	public static long getIp10(String ip) {
		long ip10 = 0;
		String[] ss = ip.trim().split("\\.");
		for (int i = 0; i < 4; i++) {
			ip10 += Math.pow(256, 3 - i) * Integer.parseInt(ss[i]);
		}

		return ip10;
	}

	/**
	 * 将十进制(如:3232235777)IP转换成IP进制(如:192.168.1.1)
	 * 
	 * @param ip10
	 * @return
	 */
	public static String getIp(long ip10) {
		String ip = "";
		long temp = 0;

		for (int i = 3; i >= 0; i--) {
			temp = ip10 / (long) Math.pow(256, i) % 256;
			if (i == 3) {
				ip = ip + temp;
			} else {
				ip = ip + "." + temp;
			}
		}

		return ip;
	}

	public static void main(String[] args) {
		System.out.println(getIp10("192.168.1.1"));
		System.out.println(getIp(getIp10("192.168.1.1")));
	}
}
 

你可能感兴趣的:(java)