Convert an IP address from an int

Source: Internet
Author: User

 

Sometimes, you need to convert the IP address to an integer for storage, and then convert it to the IP address format during reading.

1. Convert the IP string to an integer and save it

CodeAs follows:

             String Address;
Int Intaddress;
String IPaddress;
While (Address = console. Readline ())! = " \ 0 " )
{
// Convert an IP address to a byte array
Byte [] Iparr = IPaddress. parse (Address). getaddressbytes ();

// The contents stored in the byte array are displayed. The results are displayed in hexadecimal notation.
Console. writeline (bitconverter. tostring (iparr, 0 , Iparr. Length ));

// Converts a byte array to an integer type.
Intaddress = bitconverter. toint32 (iparr, 0 );
Console. writeline (intaddress );

}

Console. Readline ();

Running result:

The C0-A8-0A-11 is the output when iparr is converted to the string type, which is also the hexadecimal 192 168 10 17

285911232 is the result of iparr conversion to an integer. C0 is a decimal bit. That is to say, the integer is converted from 11-0a-a8-c0 to a decimal number. You can try it!

 

2. Convert the integer array to the IP Format

In fact, it is the first part of the inverse process. First, the integer is converted to a byte array, and then the byte array is converted to an IP address.

The Code is as follows:

 
 
//Convert an integer to an IP address
IPaddress =NewIPaddress (bitconverter. getbytes (intaddress). tostring ();

Running result:

The last line is the original IP address.

 

3. Summary

The two processes are reciprocal processes, and IP is converted to integer: IPaddress is used. getaddressbytes (), get the byte array format of the IP address, and then use bitconverter. toint32 () to convert to int. involvedAlgorithmIt is nothing more than converting the byte array to hexadecimal notation, and then converting the first value of the array to a decimal number to obtain integer data; an integer to an IP address will reverse this process.

 

 

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.