其他分享
首页 > 其他分享> > 子网掩码与prefixLength长度的互相转换

子网掩码与prefixLength长度的互相转换

作者:互联网

1、prefixLength转换成子网掩码,类似255.255.255.0

public static long calcMaskByPrefixLength(int length) {
        int mask = -1 << (32 - length);
        int partsNum = 4;
        int bitsOfPart = 8;
        int maskParts[] = new int[partsNum];
        int selector = 0x000000ff;
        for (int i = 0; i < maskParts.length; i++) {
            int pos = maskParts.length - 1 - i;
            maskParts[pos] = (mask >> (i * bitsOfPart)) & selector;
        }
        String result = "";
        result = result + maskParts[0];
        for (int i = 1; i < maskParts.length; i++) {
            result = result + "." + maskParts[i];
        }
        System.out.println(result);
        return (maskParts[0] << 24) + (maskParts[1] << 16) + (maskParts[2] << 8) + (maskParts[3]);
    }

2,子网掩码转换成prefixLength长度

 /**
     *子网掩码转成长度
     * @param netMask
     * @return
     */
    public static int calcNetMaskInt(String netMask) {
        Log.d("cnetMask", "netMask =" + netMask);
        StringBuffer sbf;
        String str;
        int prefixLength = 0, count = 0;
        String[] split = netMask.split("\\.");
        for (int n = 0; n < split.length; n++) {
            sbf = toBin(Integer.parseInt(split[n]));
            str = sbf.reverse().toString();
            //Log.e("net", split[n] + "===" + str);
            count = 0;
            for (int i = 0; i < str.length(); i++) {
                i = str.indexOf('1', i);
                if (i == -1) {
                    break;
                }
                count++;
            }
            prefixLength += count;
        }
        Log.e("cnetMask", "netMask prefixLength=" + prefixLength);
        return prefixLength;
    }


   private static StringBuffer toBin(int x) {
        StringBuffer result = new StringBuffer();
        result.append(x % 2);
        x /= 2;
        while (x > 0) {
            result.append(x % 2);
            x /= 2;
        }
        return result;
    }

标签:maskParts,int,netMask,result,长度,子网掩码,prefixLength,split
来源: https://blog.csdn.net/zhanghuaiwang/article/details/121293089