Convert the IP address to a decimal integer

Source: Internet
Author: User

The Java IP address is converted to a long integer;
Public class util {

/**
* Convert string IP address to long
* @ Param string IP Address

* Weighted by the Left shift operation, the right of the first segment is the 24 power of 2,
The second segment has the 16 power of 2,
The right of the third paragraph is the 8th power of 2,
The right of the last segment is 1.

* @ Return
*/
Public static long getstringiptolong (string IP ){
String [] IPS = IP. Split ("[.]");
Long num = 16777216l * long. parselong (IPS [0]) +
65536l * long. parselong (IPS [1]) + 256 * long. parselong (IPS [2]) +
Long. parselong (IPS [3]);
Return num;
}

/**
* Convert a long integer IP address to a string
* @ Param long type IP Address
* @ Return
*/
Public static string getlongiptostring (long iplong ){

Long mask [] = {0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000 };
Long num = 0;
Stringbuffer ipinfo = new stringbuffer ();
For (INT I = 0; I <4; I ++ ){
Num = (iplong & Mask [I])> (I * 8 );
If (I> 0) ipinfo. insert (0 ,".");
Ipinfo. insert (0, long. tostring (Num, 10 ));
}
Return ipinfo. tostring ();
}
}

**************************************** ******

The above is extracted from the Internet. The algorithm is unclear. Which expert can help explain it?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.