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

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

    The solution is to use a binary operation like

      foreach(string octet in ipAddress.Split('.'))
      {       
          int oct = int.Parse(octet);     
          while(oct !=0) 
          {
                  total += oct & 1; // {1}
                  oct >>=1;  //{2}          
          }   
      }
    

    The trick is that on line {1} the binary AND is in sence a multiplication so multiplicating 1x0=0, 1x1=1. So if we have some hypothetic number

    0000101001 and multiply it by 1 (so in binary world we execute &), which is nothig else then 0000000001, we get

    0000101001
    0000000001
    

    Most right digit is 1 in both numbers so making binary AND return 1, otherwise if ANY of the numbers minor digit will be 0, the result will be 0.

    So here, on line total += oct & 1 we add to tolal either 1 or 0, based on that digi number.

    On line {2}, instead we just shift the minor bit to right by, actually, deviding the number by 2, untill it becomes 0.

    Easy.

    EDIT

    This is valid for intgere and for byte types, but do not use this technique on floating point numbers. By the way, it's pretty valuable solution for this question.

提交回复
热议问题