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

后端 未结 5 722
借酒劲吻你
借酒劲吻你 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:29

    You can convert a number to binary like this:

            string ip = "255.255.128.0";
            string[] tokens = ip.Split('.');
            string result = "";
            foreach (string token in tokens)
            {
                int tokenNum = int.Parse(token);
                string octet = Convert.ToString(tokenNum, 2);
                while (octet.Length < 8)
                    octet = octet + '0';
                result += octet;
            }
            int mask = result.LastIndexOf('1') + 1;
    

提交回复
热议问题