智者樂山山如畫, 仁者樂水水無涯。 從從容容一盃酒, 平平淡淡一盞茶。 細雨朦朧小石橋, 春風盪漾小竹筏。 夜無明月花獨舞, 腹有詩書气自華。 吾生有崖,也知無崖,以有崖逐無崖,殆也

CIDR计算

public static string IPV4CIDR(string ipstart, string ipend) {
    var sl = ipstart.Split('.');
    var el = ipend.Split(".");
    StringBuilder sbs = new StringBuilder();
    StringBuilder sbe = new StringBuilder();
    List<char> cs = new List<char>();
    List<char> ce = new List<char>();
    foreach (var s in sl)
    {
        var t = Num2Str(int.Parse(s));
        sbs.Append(t.ToString());
        cs.AddRange(t.ToCharArray());
        //Console.WriteLine($"{s}={t}");
    }
    foreach (var s in el)
    {
        var t = Num2Str(int.Parse(s));
        sbe.Append(t.ToString());
        ce.AddRange(t.ToCharArray());
        //Console.WriteLine($"{s}={t}");
    }
    int cidr = 0;
    for (; cidr < 32; cidr++) {
        if (cs[cidr] != ce[cidr]) {
            break;
        }
    }
    List<string> iplist = new List<string>();
    int st = 0;
    do {
        int step = cidr - st > 8 ? 8 : (cidr - st);
        var one = sbs.ToString().Substring(0, step);
        var n = Str2Num(one.PadRight(8, '0'));
        iplist.Add(n.ToString());
        sbs = new StringBuilder(sbs.ToString().Substring(step, sbs.Length - one.Length));
        st += step;
    }
    while (st < cidr);

    switch (iplist.Count) {
        case 1:
            iplist.AddRange("0,0,0".Split(','));
            break;
        case 2:
            iplist.AddRange("0,0".Split(','));
            break;
        case 3:
            iplist.Add("0");
            break;
    }
    Console.WriteLine($"{string.Join('.',iplist.ToArray())}/{cidr}");
    //Console.WriteLine(sbs.ToString());
    //Console.WriteLine(sbe.ToString());
    //Console.WriteLine(cidr);
    return string.Empty;
}

public static string Num2Str(int s) {
    return Convert.ToString(s, 2).PadLeft(8, '0');
}

public static int Str2Num(string s)
{
    return Convert.ToInt32(s, 2);
}

 

posted @ 2023-12-19 12:55  後生哥哥  阅读(7)  评论(0编辑  收藏  举报
智者樂山山如畫, 仁者樂水水無涯。 從從容容一盃酒, 平平淡淡一盞茶。 細雨朦朧小石橋, 春風盪漾小竹筏。 夜無明月花獨舞, 腹有詩書气自華。 吾生有崖,也知無崖,以有崖逐無崖,殆也