Code for converting IP addresses and integers (asp.net)

Source: Internet
Author: User

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 ();
}
}

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.