Bits, bytes & format()
Octets in binary
Lesson 2 of 20 · 9 min · Module 1: Addresses are numbers
Routers do not see 192.168.1.10. They see 32 bits. Writing an address in binary is the key to understanding masks and subnets.
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…
- Convert between decimal and binary
- Pad binary numbers to a fixed width
- See an address as 32 bits
The idea
format(n, "08b") writes a number as 8 binary digits, padded with zeros: format(10, "08b") is "00001010". Each bit is worth 128, 64, 32, 16, 8, 4, 2, or 1.
print(format(192, "08b"))
print(int("11000000", 2))
01Place values
In binary, each position is worth twice the one to its right: 128, 64, 32, 16, 8, 4, 2, 1. 192 is 128 + 64, so it is 11000000.
print(format(168, "08b"))1010100002Padding matters
format(1, "b") is just "1". Networks always reason in full bytes, so "08b" pads to exactly eight digits. Without padding, the octets would not line up.
03Back again
int("10101000", 2) reads a string as a base-2 number and gives 168. Converting both ways helps you check your own work.
Your turn
to_binary(ip) that turns a valid IPv4 address into its binary form, with each octet written as 8 bits and the octets separated by dots.What the checks look for
- Converts 192.168.1.10
- Pads small values to 8 bits
- Handles 255.255.255.0
Take this with you
An IPv4 address is 32 bits; dotted decimal is only a human-friendly view of them.
Go a little further
Write from_binary(text) that converts the dotted binary form back to a normal address.