ip用int类型存储

来源:互联网 发布:在jsp中写java代码 编辑:程序博客网 时间:2024/06/14 10:02

今天再看sql优化的时候,突然看到一点说建议ip在数据库里用int类型存储,试了一下,在这里记录一下。

         /** *  * (Ip转Integer) * 方法名:ipToInteger * 创建人:Liwenbin * 时间:2017年5月2日-下午5:06:47  void * @exception  * @since  1.0.0 */public static int ipToInteger(String ip){String[] ips = ip.split("\\.");int ipFour = 0;//因为每个位置最大255,刚好在2进制里表示8位for(String ip4: ips){Integer ip4a = Integer.parseInt(ip4);//这里应该用+也可以,但是位运算更快ipFour = (ipFour << 8) | ip4a;}return ipFour;}/** *  * (Integer转IP) * 方法名:IntegerToIp * 创建人:Liwenbin * 时间:2017年5月2日-下午5:23:32  * @param ip * @return String * @exception  * @since  1.0.0 */public static String IntegerToIp(Integer ip){//思路很简单,每8位拿一次,就是对应位的IPStringBuilder sb = new StringBuilder();for(int i = 3; i >= 0; i--){int ipa = (ip >> (8 * i)) & (0xff);sb.append(ipa + ".");}sb.delete(sb.length() - 1, sb.length());return sb.toString();}


1 0
原创粉丝点击