对于ipv4地址: 192.168.1.3:
每段都用二进制表示: 192(10) = 11000000(2) ; 168(10) = 10101000(2) ; 1(10) = 00000001(2) ; 3(10) = 00000011(2) 。
所以连在一起就是:11000000101010000000000100000011,对应的int数字就是-1062731775 。
具体算法分析:
192左移24位: 11000000 00000000 00000000 00000000
168左移16位: 00000000 10101000 00000000 00000000
001左移08位: 00000000 00000000 00000001 00000000
003左移00位: 00000000 00000000 00000000 00000011
按位或的结果: 11000000 10101000 00000001 00000011
即 -1062731775
/**
** ipv4 地址转成long型数据
** @Title: fmtStrTOLong
** @Description: TODO
** @param @param ipv4Addr
** @return void
** @author CC
** @throws
*/
public static long fmtStrToLong(String ipv4Addr){
if(!validateIPV4Address(ipv4Addr)){
throw new RuntimeException("Invalid IP Address");
}
// --- 匹配数字
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(ipv4Addr);
long result = 0;
long counter = 0;
while(matcher.find()){
long value = Long.parseLong(matcher.group());
// --- 向左侧的偏移量
result = (value << 8 * (3-counter++)) | result;
}
return result;
}
/**
** 将Long转换成ipv4地址
** @Title: fmtLongToStr
** @Description: TODO
** @param @param ipv4Addr
** @param @return
** @return String
** @author CC
** @throws
*/
public static String fmtLongToStr(long ipv4Addr){
StringBuilder strBuilder = new StringBuilder();
long num = 0;
// --- 间隔.
boolean isNeedPoint = false;
for(int i = 0; i < 4; i++){
if(isNeedPoint){
strBuilder.append('.');
}
isNeedPoint = true;
int offset = 8 * (3 - i);
num = (ipv4Addr >> offset) & 0xff;
strBuilder.append(num);
}
return strBuilder.toString();
}
/**
** 验证是否是IP4地址
** @Title: validateIPV4Address
** @Description: TODO
** @param @param ipV4Addr
** @param @return
** @return boolean
** @author CC
** @throws
*/
public static boolean validateIPV4Address(String ipV4Addr){
try {
String lower = "(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])";
String regex = lower + "(\\." + lower + "){3}";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(ipV4Addr);
return matcher.matches();
} catch (Exception e) {
_LOG.info("{IPV4地址验证异常! e:"+JSONObject.toJSONString(e)+"}");
e.printStackTrace();
}
return false;
}