IP address and integer conversion implementation code of asp.net

  • 2020-05-17 05:18:00
  • OfStack

Move the n bit to the left, and multiply the value of the number by 2 to the n power
Base 2 divided by 2 is 1 bit to the right

1. Convert the IP address to an integer

How it works: each segment of the IP address can be thought of as an 8-bit unsigned integer, i.e., 0-255
1 unsigned 32 is an integer.
Example: one ip address is 10.0.3.193
The base 2 number corresponding to each segment
10 00001010
0 00000000
3 00000011
193 11000001
The combination is: 00001010 00000000 00000011 11000001, and the conversion to base 10 is: 167773121, which is the number converted from the IP address.
 
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 the integer to the IP address

How it works: convert this integer into a 32-bit base 2 number. From left to right, divide every 8 bits by 1 to get 4 8-bit binary digits, convert these to integers and then add ". This is the ip address
For example: 167773121
The base 2 representation is: 00001010 00000000 00000011 11000001
Divide into 4 segments: 00001010,00001010,00000011,11000001, convert to an integer and add "." You get 10.0.3.193.
 
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(); 
} 
} 

Related articles: