IP Address to Integer

Medium · rating 1200 · strings, math

Read an IPv4 address in dotted form a.b.c.d (each part 0–255). Print its 32-bit integer value, computed as a·224 + b·216 + c·28 + d.

Editorial

IP Address to Integer converts dotted-quad IPv4 (like 192.168.1.1) into its 32-bit integer value — a common systems/networking task.

Approach

Each of the four octets occupies 8 bits. Split on the dots and combine them positionally — a·2²⁴ + b·2¹⁶ + c·2⁸ + d — or shift-and-or each octet into place.

a, b, c, d = map(int, ip.split('.'))
return (a << 24) | (b << 16) | (c << 8) | d

Complexity

Time: O(1) — always four octets. Space: O(1).

Open IP Address to Integer in Code Arena →