Knowledge Point: a binary number, shifts n places left by bit, that is, multiplying the value of this number by the Npower of 2
Shifts one digit right after division of Binary
1. convert an IP address to an integer
Principle: each segment of an IP address can be regarded as an 8-bit unsigned integer, that is, 0-255. Each segment is split into a binary array and then converted into a binary number.
An unsigned 32 is an integer.
For example, an IP address is 10.0.3.193.
The binary number corresponding to each digit.
10 00001010
0 00000000
3 00000011
193 11000001
In combination, the IP address is 00001010 00000000 00000011 11000001, and the value is 167773121, that is, the number after the IP address is converted.Copy codeThe Code is as follows: public class Ip {
Public static void main (String [] args ){
System. out. print (ip2int ("10.0.3.193 "));
}
Public static long ip2int (String ip ){
String [] items = ip. split ("\\.");
Return Long. valueOf (items [0]) <24
| Long. valueOf (items [1]) <16
| Long. valueOf (items [2]) <8
| Long. valueOf (items [3]);
}
}
2. convert an integer to an IP address
Principle: convert this integer into a 32-bit binary number. Split each eight bits from left to right to get the 4-Segment 8-bit binary number. convert these binary numbers into integers and then add "." This is the IP address.
Example: 167773121
Binary representation: 00001010 00000000 00000011 11000001
Split into four segments:, and. convert them into integers and add "." 10.0.3.193 is displayed.Copy codeThe Code is as follows: public class Ip {
Public static void main (String [] args ){
System. out. print (int2ip (167773121 ));
}
Public static String int2ip (long ipInt ){
StringBuilder sb = new StringBuilder ();
Sb. append (ipInt & 0xFF). append (".");
Sb. append (ipInt> 8) & 0xFF). append (".");
Sb. append (ipInt> 16) & 0xFF). append (".");
Sb. append (ipInt> 24) & 0xFF );
Return sb. toString ();
}
}