最近剛參與一個小項目畔况,看到同事在設計數(shù)據(jù)庫的時候,ipv4地址使用的類型是varcahr(50)進行存儲慧库,瞬間感覺好low啊跷跪。。齐板。
我們有兩周方法解決這種性能問題:
1.mysql的inet_aton和 inet_ntoa函數(shù)來完成吵瞻,例如:
2.使用java代碼,按位運算來實現(xiàn)轉換(推薦)甘磨,代碼如下:
思路:
我的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的數(shù)字
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代碼從我做起济舆!