字符型的IPV4地址转int型存储

最近刚参与一个小项目,看到同事在设计数据库的时候,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代码从我做起!

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1.1 IP地址基础 什么是IP地址:IP地址是可以唯一表示IP网络中的每台设备。 每台...
    ssdsss阅读 5,887评论 0 1
  • IP地址的分类(记住) IP地址分为A类、B类、C类、D类、E类,规定如下: A类:网络位8位,主机位24位,网络...
    Arya鑫阅读 14,430评论 1 18
  • 他从梦魇中醒来, 世界是亮着LED灯的屋顶, 灯光刺眼, 透着冰冷的惨白, 人影憧憧, 动一动手指, 抵触到凉凉的...
    汀甘棠阅读 4,138评论 18 14
  • 试想一下这样的场景: 门前的锁钥匙不见了,你会怎么办呢? 是盯着锁,还是到别的地方其找找钥匙呢?答案不言而明,当然...
    屠龙女青年阅读 2,828评论 1 1
  • 每当节假日时 深圳的周围 都挂上了 红色的丝带 甚至紫色的 总是 进出不易 其实 他是...
    桓舟子阅读 715评论 2 0