One IPv4 address can be written as dotted decimal, as 32 bits, or as one number.
What to build
A program that converts a dotted IPv4 address into its number and its binary form.
Requirements
- Print
number N, where N is the address read as one 32-bit number. - Print
binary B, where B is the four bytes in 8-digit binary, joined with dots.
Input
One valid IPv4 address.
Output
Two lines: number N and binary B.
Constraints
Each part is between 0 and 255.
Example
Input:
192.168.1.10
Output:
number 3232235786
binary 11000000.10101000.00000001.00001010
Why it works
The four parts are the four bytes of one 32-bit number. Multiplying by 256 as you go shifts the earlier bytes left by one byte each time.
Examples
Example 1 · Input
192.168.1.10
Expected output
number 3232235786 binary 11000000.10101000.00000001.00001010
Example 2 · Input
10.0.0.1
Expected output
number 167772161 binary 00001010.00000000.00000000.00000001
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Start with n = 0, then for each part: n = n * 256 + int(part).
Hint 2
format(int(part), "08b") writes a byte as 8 binary digits.
Hint 3
Join the four binary groups with dots.
Solution
Show one correct solution (try it yourself first)
ip = input().strip()
n = 0
bits = []
for part in ip.split("."):
n = n * 256 + int(part)
bits.append(format(int(part), "08b"))
print("number", n)
print("binary", ".".join(bits))
▶ Open this solution in the compiler, then press Visualize to watch it run step by step