Knowledge Point: A binary number, bitwise left n bit, is to multiply the value of the number by 2 of the n-th side
Binary is one of the two right shifts
1. Convert IP address to integer
Principle: IP address can be considered as a 8-bit unsigned integer that is 0-255, split each segment into a binary form, and then convert the binary number to
An unsigned 32 is an integer.
Example: An IP address for 10.0.3.193
Number of binary digits corresponding to each segment
10 00001010
0 00000000
3 00000011
193 11000001
The combination is: 00001010 00000000 00000011 11000001, converted to 10 is: 167773121, that is, the IP address after the conversion of the number is it.
Copy Code code 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 integer to IP address
Principle: Converts this integer to a 32-bit binary number. From left to right, every 8 bits are split, get 4 8-bit binary numbers, convert these binary numbers to integers and add ". "That's the IP address.
Example: 167773121
Binary representations are: 00001010 00000000 00000011 11000001
Split into four segments: 00001010,00001010,00000011,11000001, converted to integers, plus ". "I got 10.0.3.193.
Copy Code code 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 >>) & 0xFF). Append (".");
Sb.append (Ipint >>) & 0xFF);
return sb.tostring ();
}
}