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.
However, I need to be able to do this in C# WITHOUT the use of the System.Net library (the system I am programming in does not have access to this library).
It seems like the process should be something like:
1) Split the Subnet Mask into Octets.
2) Convert the Octets to be binary.
3) Count the number of Ones in each Octet.
4) Output the total number of found Ones.
However, my C# is pretty poor. Does anyone have the C# knowledge to help?
Bit counting algorithm taken from:
http://www.necessaryandsufficient.net/2009/04/optimising-bit-counting-using-iterative-data-driven-development/
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.
You can convert a number to binary like this:
The solution is to use a
binary operation
likeThe trick is that on line {1} the
binary AND
is in sence a multiplication so multiplicating1x0=0
,1x1=1
. So if we have some hypothetic number0000101001
and multiply it by1
(so in binary world we execute &), which is nothig else then0000000001
, we getMost right digit is
1
in both numbers so makingbinary AND
return1
, otherwise if ANY of the numbers minor digit will be0
, the result will be0
.So here, on line
total += oct & 1
we add totolal
either1
or0
, 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 becomes0
.Easy.
EDIT
This is valid for
intgere
and forbyte
types, but do not use this technique onfloating point
numbers. By the way, it's pretty valuable solution for this question.A complete sample: