Conversion between IP address and integer implementation code (asp.net) _ Practical Tips

Source: Internet
Author: User
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 ();
}
}

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.