最近刚参与一个小项目,看到同事在设计数据库的时候,ipv4地址使用的类型是varcahr(50)进行存储,瞬间感觉好low啊。。。
微信截图_20181128155147.png
我们有两周方法解决这种性能问题:
1.mysql的inet_aton和 inet_ntoa函数来完成,例如:
微信截图_20181128155207.png
2.使用java代码,按位运算来实现转换(推荐),代码如下:
思路:
我的ip:192.168.159.135
每段都可以用二进制表示:
192(10) = 11000000(2) ; 168(10) = 10101000(2) ;
159(10) = 10011111(2) ; 135(10) = 10000111(2)
192左移24位: 11000000 00000000 00000000 00000000
168左移16位: 00000000 10101000 00000000 00000000
159左移08位 : 00000000 00000000 10011111 00000000
135左移00位: 00000000 00000000 00000000 10000111
最后按位或得出结果:
11000000 10101000 10011111 10011111
代码如下
package com.buka.algorithm;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class IPConvert {
/**
* 判断是否为ipv4地址
*
*/
private static boolean isIPv4Address(String ipv4Addr) {
String lower = "(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])"; // 0-255的数字
String regex = lower + "(\\." + lower + "){3}";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(ipv4Addr);
return matcher.matches();
}
public static int ipToInt(String ip) {
if (!isIPv4Address(ip))
throw new RuntimeException("ip地址错误!");
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(ip);
int result = 0;
int counter = 0;
while(matcher.find()) {
int value = Integer.parseInt(matcher.group());
result = (value << 8 * (3 - counter++)) | result;
}
return result;
}
public static String intToIP(int ipNum) {
StringBuilder sb = new StringBuilder();
int num = 0;
boolean needPoint = false;
for (int i=0; i<4; i++) {
if (needPoint)
sb.append(".");
needPoint = true;
int offset = 8 * (3 - i);
num = (ipNum >> offset) & 0xff;
sb.append(num);
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println(intToIP(-1062690937));
}
}
拒绝low代码从我做起!
网友评论