, 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]);
}