不做嵌入式开发,很少有机会直接做二进制数据的操作,最近要在数据库里存放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。