How many hosts fit in a CIDR block
An IPv4 CIDR prefix carves out a block of addresses. Two are reserved — the network address and the broadcast — so the rest are usable hosts.
- The number of usable hosts is 2^(32 − prefixBits) − 2.
- When prefixBits is less than 1 or 31 or more, return 0.
- Compute the power of two by repeated doubling, not a library function.
CidrHosts(prefixBits: int) → int
C# needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
public int CidrHosts(int prefixBits) {
}
Worked examples
| Call | Result |
|---|---|
CidrHosts(24) | 254 |
CidrHosts(8) | 16777214 |
CidrHosts(16) | 65534 |
CidrHosts(31) | 0 |
Hint
Start at 1 and double it (32 − prefixBits) times.
Reference solution in C#
public int CidrHosts(int prefixBits) {
if (prefixBits < 1 || prefixBits >= 31) return 0;
int exp = 32 - prefixBits;
int hosts = 1;
for (int i = 0; i < exp; i++) hosts = hosts * 2;
return hosts - 2;
}