IPv4 Address to Integer
Problem Statement
Convert a dotted-quad IPv4 address string to its 32-bit integer value.
Background
Each of the four octets contributes 8 bits: the integer is a*2563 + b256**2 + c256 + d**, i.e. the big-endian packing of the four bytes.
Your Task
def ip_to_int(ip):
Return the integer value of the address.
Input Format
- ip (str): "a.b.c.d" with each octet 0..255.
Output Format
- A single int.
Sample
print(ip_to_int("192.168.1.1"))
Output:
3232235777
Example:
print(ip_to_int("192.168.1.1"))3232235777
- Split the input string
"192.168.1.1"by dots to extract the four octets: 192, 168, 1, 1. - Initialize the accumulator to 0 and process the first octet (192): 0×256+192=192.
- Process the second octet (168) by shifting the previous value left by 8 bits (multiplying by 256) and adding the new byte: 192×256+168=49152+168=49320.
- Process the third octet (1): 49320×256+1=12625920+1=12625921.
- Process the fourth octet (1): 12625921×256+1=3232235776+1=3232235777.
- The final output is 3232235777
Constraints:
- Four octets, each 0..255.
- Big-endian: leftmost octet is most significant.
- Return an int.
1. Background Knowledge
An IPv4 address is a 32-bit identifier composed of four 8-bit segments called octets, typically written in dotted-decimal notation (e.g., 192.168.1.1). Each octet ranges from 0 to 255. When stored or transmitted in network byte order, these four bytes are packed into a single 32-bit integer using big-endian representation, meaning the first octet occupies the most significant byte (bits 24–31), the second octet occupies bits 16–23, and so on.
The conversion from dotted-quad to integer is essentially a base-256 positional encoding. If the octets are a,b,c,d, the resulting integer is:
value=aâ‹…2563+bâ‹…2562+câ‹…256+dThis mirrors how decimal digits work: the leftmost digit has the highest place value. In binary terms, you are concatenating four 8-bit chunks into one 32-bit word.
2. Algorithm Approach
The core pattern here is iterative base conversion or bit shifting. You can process the octets from left to right, accumulating the result by shifting the current value left by 8 bits and adding the next octet. This avoids explicitly computing powers of 256 and naturally handles the big-endian ordering.
Alternatively, you can compute the weighted sum directly using the formula above. Both approaches are valid; the shifting method is often preferred in systems programming because it maps directly to how hardware handles byte packing.
3. Step-by-Step Strategy
Continue the full explanation
You're reading the free preview. Unlock the complete walkthrough, the code editor, test runner and reference solution with Premium.
Editor locked
The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.