首页 > 编程知识 正文

ip地址转换为点分十进制,ip地址点分十进制转换成二进制

时间:2023-05-04 15:18:45 阅读:225756 作者:2241

不做嵌入式开发,很少有机会直接做二进制数据的操作,最近要在数据库里存放ip,为了节省空间,mysql的inet_aton() inet_ntoa()函数又不太方便用,就自己写了个转化的程序。

public static long stringToAddress(String ipString) throws BadIPException {

if (ipString == null) {

throw new BadIPException(ipString);

}

String[] ipParts = ipString.split("\.");

if (ipParts.length != 4) {

throw new BadIPException(ipString);

}

byte[] bytes = new byte[4];

try {

for (int i = 0; i < 4; i++) {

int intValue = Integer.parseInt(ipParts[i]);

if (intValue < 0 || intValue > 255) {

throw new BadIPException(ipString);

}

bytes[i] = (byte) intValue;

}

} catch (NumberFormatException e) {

throw new BadIPException(ipString);

}

long ipAddress = 0x00000000000000FF & bytes[0];

for (int i = 1; i < 4; i++) {

ipAddress <<= 8; ipAddress |= 0x00000000000000FF & bytes[i];

}

return ipAddress;

}

public static String addressToString(long address) {

if (address < 0) {

throw new BadIPException(address);

}

long part1 = address & 0x00000000FF000000;

part1 >>>= 24;

long part2 = address & 0x0000000000FF0000;

part2 >>>= 16;

long part3 = address & 0x000000000000FF00;

part3 >>>= 8;

long part4 = address & 0x00000000000000FF;

return part1 + "." + part2 + "." + part3 + "." + part4;

}

由于java没有无符号的int类型,免得麻烦,就用了long。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。