首页 > 编程语言 > 详细

Java将ip字符串转换成整数的代码

时间:2019-04-28 11:43:40      阅读:114      评论:0      收藏:0      [点我收藏+]

下面代码是关于Java将ip字符串转换成整数的代码,希望对各位有较大用途。


public class IpUtil {

public static int Ip2Int(String strIp){
String[] ss = strIp.split("\.");
if(ss.length != 4){
return 0;
}
byte[] bytes = new byte[ss.length];
for(int i = 0; i < bytes.length; i++){
bytes[i] = (byte) Integer.parseInt(ss[i]);
}
return byte2Int(bytes);
}
public static String int2Ip(int intIp){
byte[] bytes = int2byte(intIp);
StringBuilder sb = new StringBuilder();
for(int i = 0; i < 4; i++){
sb.append(bytes[i] & 0xFF);
if(i < 3){
sb.append(".");
}
}
return sb.toString();
}

private static byte[] int2byte(int i) {
byte[] bytes = new byte[4];
bytes[0] = (byte) (0xff & i);
bytes[1] = (byte) ((0xff00 & i) >> 8);
bytes[2] = (byte) ((0xff0000 & i) >> 16);
bytes[3] = (byte) ((0xff000000 & i) >> 24);
return bytes;
}
private static int byte2Int(byte[] bytes) {
int n = bytes[0] & 0xFF;
n |= ((bytes[1] << 8) & 0xFF00);
n |= ((bytes[2] << 16) & 0xFF0000);
n |= ((bytes[3] << 24) & 0xFF000000);
return n;
}

public static void main(String[] args) {
String ip1 = "192.168.0.1";
int intIp = Ip2Int(ip1);
String ip2 = int2Ip(intIp);
System.out.println(ip2.equals(ip1));
}
}





 

Java将ip字符串转换成整数的代码

原文:https://www.cnblogs.com/xwyto/p/10782389.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!