当前位置:网站首页>IP and long integer interchange

IP and long integer interchange

2022-07-07 14:04:00 It is small new

IP Swap with long integer
 * 
 *
 */
public class IPUtil {
    public static void main(String[]args){
        String ip="126.56.78.59";
        long ipLong=ipToLong(ip);
        System.out.println(ipLong);
        System.out.println(longToIP(ipLong));
        
    }
    /**
     * take 127.0.0.1 Formal IP The address is converted to a decimal integer   There is no error handling here
     * Move left operation (<<) Weight each number The power of the first paragraph is 2 Of 24 Power The power of the second paragraph is 2 Of 16 Power
     * The power of the third paragraph is 2 Of 8 Power The last paragraph is 1
     */
    public static long ipToLong(String ipadress){
        long[]ip=new long[4];
        // First find IP In the address string . The location of
        int position1=ipaddress.indexOf(".");
        int position2=ipaddress.indexOf(".",position1+1);
        int position3=ipaddress.indexOf(".",position2+1);
        // Each one . Convert the string between to integer  
        ip[0]=Long.parseLong(ipadress, substring(0,position1));
        ip[1] = Long.parseLong(ipaddress.substring(position1 + 1, position2));
        ip[2] = Long.parseLong(ipaddress.substring(position2 + 1, position3));
        ip[1] = Long.parseLong(ipaddress.substring(position3 + 1));
        return (ip[0]<<24)+(ip[1]<<16)+(ip[2]<<8)+ip[3];
        
    }
/**
 * Convert decimal integer form to 127.0.0.1 Formal IP Address Move the integer value to the right (>>) Move right 24 position , When moving to the right, the high position makes up 0, The number obtained is the first paragraph IP.
 * adopt & The operator Set the high order of the integer value to 0, Move right again 16 position The number obtained is the second paragraph ip
 * The high of the integer value through the and operator 16 Set as 0, Move right again 8 position , The number obtained is the third paragraph IP.
                    The high of the integer value through the and operator 24 Set as 0, The figure obtained is the fourth paragraph IP.
                    
 */
    public static String longToLong(long ipaddress){
        StringBuffer sb=new StringBuffer("");
        // Move right directly 24 position
        sb.append(String.valueOf((ipaddress>>>24)));
        sb.append(".");
        // Will be high 8 Location 0 And then move right 16 position
        sb.append(String.valueOf((ipaddress&0x00FFFFFF)>>>16));
        sb.append(".");
        // Will be high 16 Location 0 And then move right 8 position
        sb.append(String.valueOf((ipaddress&0x0000FFFF)>>>8));
        sb.append(".");
        // Will be high 24 Location 0
        sb.append(String.valueOf((ipaddress & 0x000000FF)));
        return sb.toString();
        
    }
}

原网站

版权声明
本文为[It is small new]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202130616018404.html