java ip转成数值的用途_Java将ip字符串转换成整数的代码

下面代码是关于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));

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值