java将IP地址转换为数字以及逆向转换(位运算和0xFF的使用)第二季

原文:

http://www.mkyong.com/java/java-convert-ip-address-to-decimal-number/


来自同一个博客。


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;
	}
	return result.toString();
  }

  //ip = 3232235778
  public String longToIp2(long ip) {
 
	return ((ip >> 24) & 0xFF) + "." 
		+ ((ip >> 16) & 0xFF) + "." 
		+ ((ip >> 8) & 0xFF) + "." 
		+ (ip & 0xFF);
  }


完整代码:

public class JavaBitwiseExample {
 
	public static void main(String[] args) {
 
		JavaBitwiseExample obj = new JavaBitwiseExample();
 
		System.out.println("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);
 
		}
 
		return 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) {
		StringBuilder 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();
	}
}

Output:

iptoLong  : 3232235778
iptoLong2 : 3232235778
longToIp  : 192.168.1.2
longToIp2 : 192.168.1.2


展开阅读全文

没有更多推荐了,返回首页