A prefix such as /26 and a mask such as 255.255.255.192 say the same thing.
What to build
A program that turns a prefix length into a subnet mask and a host count.
Requirements
- Print
mask M, with M in dotted decimal. - Print
hosts H, the number of usable host addresses (2 to the power of the host bits, minus 2).
Input
One whole number: the prefix length.
Output
Two lines: mask M and hosts H.
Constraints
0 ≤ prefix ≤ 30.
Example
Input:
26
Output:
mask 255.255.255.192
hosts 62
Why it works
A mask has p ones and then zeros. Writing it as one number and cutting it into four bytes gives the dotted form, and the host bits are 32 − p, so there are 2 to that power minus the two special addresses.
Examples
26
mask 255.255.255.192 hosts 62
24
mask 255.255.255.0 hosts 254
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
The mask is p ones followed by 32 - p zeros: ((1 << p) - 1) << (32 - p).
Hint 2
Read the four bytes with (mask >> shift) & 255 for shift 24, 16, 8, 0.
Hint 3
Usable hosts: 2 ** (32 - p) - 2.
Solution
Show one correct solution (try it yourself first)
p = int(input())
mask = ((1 << p) - 1) << (32 - p)
parts = [str((mask >> s) & 255) for s in (24, 16, 8, 0)]
print("mask", ".".join(parts))
print("hosts", 2 ** (32 - p) - 2)
▶ Open this solution in the compiler, then press Visualize to watch it run step by step