'Get netmaske from CIDR

How do I get the netmask of any CIDR, e.g.
CIDR=10 > 255.255.0.0
CIDR=24 > 255.255.255.0
CIDR=25 > 255.255.255.128
CIDR=31 > 255.255.255.254



Solution 1:[1]

This will create a byte[4] array with the four netmask octet. You assign your CIDR to the variable CIDRInt

int CIDRInt = 26;
int index = 0;
byte[] CIDROctet = new byte[4] { 0, 0, 0, 0 };

for (int i = 1; i <= 32; i++)
{
    if (i > CIDRInt) { break; }
    if (index == 8) { index = 0; }

    if (i > 24)
    {
        CIDROctet[3] |= (byte)(1 << (7 - index)); //index from 7 til -1
        index++;
    }
    else if (i > 16)
    {
        CIDROctet[2] |= (byte)(1 << (7 - index));
        index++;
    }
    else if (i > 8)
    {
        CIDROctet[1] |= (byte)(1 << (7 - index)); 
        index++;
    }
    else
    {
        CIDROctet[0] |= (byte)(1 << (7 - index));
        index++;
    }
}

string CIDRStr = CIDROctet[0] + "." + CIDROctet[1] + "." + CIDROctet[2] + "." + CIDROctet[3];

UPDATE:
I like the idea of calculating the netmask as above, but I ended up creating a "low-tech" class with manual static mappings of CIDR<>Netmask for assumable better performance and two-way-convertion. The class also return the netmask-class (A, B or C) and the amount of covered IP addresses of each netmask. The class is available at github.com

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1