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.