CIDR notation & bitwise operators
Prefix length and subnet masks
Lesson 3 of 20 · 10 min · Module 1: Addresses are numbers
192.168.1.0/24 means "the first 24 bits are the network". The same idea written the old way is the subnet mask 255.255.255.0.
Start this lesson →Free. No installation: you write and run the code in your browser, and it is checked automatically.
By the end, you’ll be able to…
- Relate prefix length to a subnet mask
- Use shifts and masks on integers
- Split a 32-bit number into octets
The idea
A mask is 32 bits: the first prefix bits are 1 and the rest are 0. Build it with bit operators: (0xFFFFFFFF << (32 - prefix)) & 0xFFFFFFFF. Then split it into four octets with >> (shift right) and & 255 (keep the lowest 8 bits).
mask = (0xFFFFFFFF << 8) & 0xFFFFFFFF
print(bin(mask))
print(mask >> 24 & 255)
01A mask is ones, then zeros
/26 means 26 ones followed by 6 zeros. The last octet is 11000000, which is 192, so the mask is 255.255.255.192.
print(prefix_to_mask(26))255.255.255.19202Shifting moves bits
x << 8 moves every bit 8 places left and fills the right with zeros. Starting from 32 ones, shifting left by (32 - prefix) leaves exactly prefix ones on the left.
03Keep 32 bits, then slice bytes
Python integers can grow beyond 32 bits, so & 0xFFFFFFFF trims the result. (mask >> 16) & 255 moves the second octet to the bottom and keeps only those 8 bits.
Your turn
prefix_to_mask(prefix) that returns the dotted subnet mask for a prefix length from 0 to 32, for example "255.255.255.0" for 24.What the checks look for
- Converts /24, /16 and /8
- Converts prefixes that end inside an octet
- Handles the extremes /0 and /32
Take this with you
A prefix length counts the leading ones in the mask.
Go a little further
Write mask_to_prefix(mask) that counts the ones in a dotted mask using bin(…).count("1").