1 Star 6 Fork 1

蔚蔚樱软件开发/AlgoHub

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
TransIP2Int.java 2.13 KB
一键复制 编辑 原始数据 按行查看 历史
ljfirst 提交于 2022-11-18 20:47 +08:00 . feat:TheLastKOfLink 链表的倒数第K个元素
package DataStructure.stringOps.stringAndSequence;
import Common.Constant.C;
import Common.Utils.UTFactory;
import org.junit.Test;
/**
* @author 蔚蔚樱
* @version 1.0
* @date 2018-8-28 下午02:14:14
* @author—Email micromicrohard@outlook.com
* @description IP地址转化
* 将string类型的IP地址转化成数字
* 示例:"0.0.1.0" => 256
* @attention 考虑到int类型的最大长度为32位,在计算的时候会出现问题,因此乘积选用long类型来存储。
*/
public class TransIP2Int {
@Test // 验证功能:从数据库获取测试数据,用于单元测试
public void TestFunc() throws Exception {
UTFactory.FullTest(this.getClass());
}
@Test // 调试功能 : 用于复现错误的测试案例
public void DoubleTrack() throws Exception {
String input = "256.0.0.0";
String output = "ErrorExpr";
UTFactory.DebugTest(this.getClass(), input, output);
}
public long transMethod(String ipExpr) {
if (ipExpr == null || ipExpr.length() == 0) {
return C.ErrorNum;
}
//正则表达式对IP进行判断
ipExpr = ipExpr.trim();
String regular = "^[0-9]{1,3}[.][0-9]{1,3}[.][0-9]{1,3}[.][0-9]{1,3}$";
if (!ipExpr.matches(regular)) {
return C.ErrorNum;// throw new Exception("IP地址有误!");
}
//注意1:如果用“.”作为分隔的话,必须是如下写法,String.split("\\."),这样才能正确的分隔开,不能用String.split(".");
//注意2:IP地址检查。
String[] ipArray = ipExpr.split("\\.");
int hex = 8;
long intExpr = 0;
for (int i = 0; i < ipArray.length; i++) {
long num = Integer.parseInt(ipArray[i]);
if (num > 255) {
return C.ErrorNum;//throw new Exception("IP地址超过255");
}
//注意:先乘除,确定移位数,再移位,hex是8的倍数,每次移动8,16,24位
num = num << (ipArray.length - i - 1) * hex;
//num <<= (ipArray.length - i - 1) * hex;
intExpr += num;
}
return intExpr;
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/micromicrohard/algo-hub.git
git@gitee.com:micromicrohard/algo-hub.git
micromicrohard
algo-hub
AlgoHub
master

搜索帮助