ipv4字符串转long数字

/ java / 0 条评论 / 2927浏览

IPv4字符串转换成Long类型的数字

转换逻辑

ipv4的值的范围是0~255,在二进制下最大值是8位;转换long时,实际是将ip的每段分别存储在二进制的不同位置,互不干扰。

所以做乘法(<<)时,最少要是2的8次方。

比如:2的0、8、16、24次方或者0、9、18、27。

long转ip时,要保证值的大小不超过ipv4的范围255,所以要进行位于运算 &0xFF

代码

public static void main(String[] args) {

    String ip = "127.0.0.1";

    System.out.println(0xFF);

    long ipLong2 = ipToLong2(ip);
    System.out.println("ip=" + ip + ", long = " + ipLong2);
    System.out.println("--------------");
    System.out.println("long=" + ipLong2 + ", ip=" + longToIp2(ipLong2));
}

/**
 * ip转数字
 * @param ip
 * @return
 */
public static Long ipToLong2(String ip) {
    String[] ips = ip.split("\\.");
    long a1 = Long.parseLong(ips[0]) << 27;
    long a2 = Long.parseLong(ips[1]) << 18;
    long a3 = Long.parseLong(ips[2]) << 9;
    long a4 = Long.parseLong(ips[3]);
    System.out.println(a1);
    System.out.println(a2);
    System.out.println(a3);
    System.out.println(a4);

    System.out.println("二进制--------");
    System.out.println(Long.toBinaryString(a1));
    System.out.println(Long.toBinaryString(a2));
    System.out.println(Long.toBinaryString(a3));
    System.out.println(Long.toBinaryString(a4));
    System.out.println("二进制--------");

    return (a1) + (a2) + (a3) + (a4);
}

/**
 * 数字转ip
 *
 * @param data
 * @return
 */
public static String longToIp2(long data) {
    Long a1 = (data >>> 27) & 0xFF;
    Long a2 =(data >>> 18) & 0xFF;
    Long a3 = (data >>> 9) & 0xFF;
    Long a4 = data & 0xFF;
    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append(a1).append(".");
    stringBuilder.append(a2).append(".");
    stringBuilder.append(a3).append(".");
    stringBuilder.append(a4);

    System.out.println(a1);
    System.out.println(a2);
    System.out.println(a3);
    System.out.println(a4);
    return stringBuilder.toString();
}
评论已关闭.