The conversion of Java mask IP and the number of digits

Source: Internet
Author: User

, one, mask-shaped such as: "255.255.255.0" into the number of digits 24, the idea is as follows:

To determine if the passed-in mask string is IP, the simplest method is to match directly, with the following code:

Import Java.util.regex.Matcher;
Import Java.util.regex.Pattern;

public static Boolean Ismask (String mask) {
Pattern pattern = Pattern.compile ("^ (\\d{1,3}\\.)  {3}\\d{1,3}$) "); Return Pattern.matcher (Mask). Matches ();
}
2. Determine the number of IP 1, I use the idea of the mask into the plastic, the plastic to judge the number of 1. 2.1 Convert IP to Plastic
public static int Iptoint (String ipaddr) {

if (!ismask (IPADDR))
return 0;
string[] Iparr = Ipaddr.split ("\;");

Return ((Integer.parseint (iparr[0) & 0xFF) <<24) + ((Integer.parseint (iparr[1)) & 0xFF) << 16)
+ ((Integer.parseint (iparr[2]) & 0xFF)) << 8 + ((Integer.parseint (iparr[3) & 0xFF));

}



2.2 Number 1 operations on integers:

Public staticint findNumberOf1 (int n)
{
int countof1=0;
int tag=1;
while (tag!= 0)
{
if ((tag&n)!=0)
countof1++;
tag=tag<<1;
}
return COUNTOF1;
}

Second, the mask number of digits into the IP form, the idea is as follows:

public static String inttomask (int bitmask)
{
if (Bitmask > 32)
return null;

int tmpmask[] = {0,0,0,0};
int times = BITMASK/8;
int i = 0;
for (; I < times; i++)
{
Tmpmask[i] = 255;
}

for (int j = 1; J <= 8; j + +)
{
if (J <= bitmask-times*8)
Tmpmask[i] = 2*tmpmask[i] + 1;
Else
Tmpmask[i] = 2*tmpmask[i];
}

Return integer.tostring (tmpmask[0]) + "." + integer.tostring (tmpmask[1]) + "." + integer.tostring (tmpmask[2]) + "." + I Nteger.tostring (Tmpmask[3]);
}






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.