MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / decimal_to_ipv4

Function decimal_to_ipv4

conversions/ipv4_conversion.py:51–79  ·  view source on GitHub ↗

Convert a decimal representation of an IP address to its IPv4 format. Args: decimal_ipv4: An integer representing the decimal IP address. Returns: The IPv4 representation of the decimal IP address. >>> decimal_to_ipv4(3232235521) '192.168.0.1' >>> decimal_

(decimal_ipv4: int)

Source from the content-addressed store, hash-verified

49
50
51def decimal_to_ipv4(decimal_ipv4: int) -> str:
52 """
53 Convert a decimal representation of an IP address to its IPv4 format.
54
55 Args:
56 decimal_ipv4: An integer representing the decimal IP address.
57
58 Returns:
59 The IPv4 representation of the decimal IP address.
60
61 >>> decimal_to_ipv4(3232235521)
62 '192.168.0.1'
63 >>> decimal_to_ipv4(167772415)
64 '10.0.0.255'
65 >>> decimal_to_ipv4(-1)
66 Traceback (most recent call last):
67 ...
68 ValueError: Invalid decimal IPv4 address
69 """
70
71 if not (0 <= decimal_ipv4 <= 4294967295):
72 raise ValueError("Invalid decimal IPv4 address")
73
74 ip_parts = []
75 for _ in range(4):
76 ip_parts.append(str(decimal_ipv4 & 255))
77 decimal_ipv4 >>= 8
78
79 return ".".join(reversed(ip_parts))
80
81
82if __name__ == "__main__":

Callers

nothing calls this directly

Calls 1

appendMethod · 0.45

Tested by

no test coverage detected