Calculating the number of bits in a Subnet Mask in C#

后端 未结 5 664
借酒劲吻你
借酒劲吻你 2021-01-14 06:47

I have a task to complete in C#. I have a Subnet Mask: 255.255.128.0.

I need to find the number of bits in the Subnet Mask, which would be, in this case, 17.

5条回答
  •  别那么骄傲
    2021-01-14 07:33

    Bit counting algorithm taken from:
    http://www.necessaryandsufficient.net/2009/04/optimising-bit-counting-using-iterative-data-driven-development/

    string mask = "255.255.128.0";
    int totalBits = 0;
    foreach (string octet in mask.Split('.'))
    {
        byte octetByte = byte.Parse(octet);
        while (octetByte != 0)
        {
            totalBits += octetByte & 1;     // logical AND on the LSB
            octetByte >>= 1;            // do a bitwise shift to the right to create a new LSB
        }                
    }
    Console.WriteLine(totalBits);
    

    The most simple algorithm from the article was used. If performance is critical, you might want to read the article and use a more optimized solution from it.

提交回复
热议问题