Decode a Hex String into a Dotted-Quad Network Address
StringsAuto-graded · 28 test casesLast updated
Validate a strict 8-digit hex string with an optional 0x prefix and convert it into dotted-decimal IPv4 form, treating the leftmost byte as the first octet.
Hex to Dotted-Quad Address
A 32-bit network address is sometimes stored as a string of hexadecimal digits. Your job is to turn such a string into the familiar dotted-decimal IPv4 form.
Write a function that receives one string text and returns either the dotted-decimal address or the literal string INVALID.
Rules
Accepted input
- The string may begin with a single
0xor0Xprefix. After that optional prefix is removed, exactly eight hexadecimal digits must remain. - Hexadecimal digits are
0-9,a-fandA-F. Upper and lower case may be mixed freely. - Nothing else is allowed. Whitespace,
+or-signs, separators such as.,:or_, and any other characters make the input invalid. Strings that are too short or too long after the prefix is removed are invalid as well. - Only one prefix is removed. For example,
0x0x...is not valid, because the second0xstays in the string and counts as extra characters. - An empty string, or a string consisting only of the prefix, is invalid.
Byte order
- Use network order (big-endian): the leftmost two hex digits give the first octet, the next two give the second octet, and so on.
Output
- For valid input, return the four octets in decimal, separated by single dots, with no leading zeroes (a zero octet is written
0). - For invalid input, return exactly
INVALID.
Signed values
- Treat the eight digits as an unsigned 32-bit pattern. Addresses whose top bit is set (first octet 128 or above) are perfectly valid and must never come out negative.
Constraints
0 <= len(text) <= 100textis an arbitrary string, which may contain characters outside the hexadecimal alphabet.- The function returns a string: either a dotted-decimal address or
INVALID.
Examples
Example 1
Input: hex_to_dotted_quad('C0A80101')
Output: '192.168.1.1'
Example 2
Input: hex_to_dotted_quad('0xffffffff')
Output: '255.255.255.255'
Example 3
Input: hex_to_dotted_quad('00000000')
Output: '0.0.0.0'
Example 4
Input: hex_to_dotted_quad('1FF')
Output: 'INVALID'
Hints
Hint 1
Handle the optional prefix first: drop one leading 0x or 0X, then check what is left. The remaining text must be exactly 8 characters long.
Hint 2
Check each remaining character against an explicit set of allowed hex characters rather than relying on a library parse to fail. Built-in parsers often tolerate signs, spaces or underscores.
Hint 3
Convert the string two characters at a time (indices 0-2, 2-4, 4-6, 6-8). Each pair is a value from 0 to 255, so no large or negative intermediate number appears, and printing it as an int removes leading zeroes.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
An IPv4 address is four bytes, and each byte is exactly two hex digits. So a valid 8-digit hex string splits cleanly into four pairs, read left to right, and each pair is converted from base 16 to base 10.
- Validate strictly. Remove at most one leading
0xor0X. The remaining text must be exactly 8 characters, and each character must belong to an explicit whitelist of hex digits (0-9,a-f,A-F). If either check fails, returnINVALID. - Convert pairwise. Parse
text[0:2],text[2:4],text[4:6]andtext[6:8]as base-16 integers, turn each into a decimal string, and join the four strings with dots.
Why it is correct
- After validation there are exactly eight hex digits, i.e. 32 bits. Pair
kholds bits31-8kdown to24-8k, which is bytekin big-endian order, and that is by definition octetk+1in network order. - Each pair parses to a value in
[0, 255]. Converting an integer to a string never adds leading zeroes, so"01"becomes1and"00"becomes0, as the output format requires. - Because every pair is handled on its own, no value ever approaches a 32-bit signed boundary. Addresses with the high bit set, such as
FFFFFFFF, therefore produce255.255.255.255and never a negative number. In languages with fixed-width signed integers, parsing the whole value and shifting would need masking with& 0xFF; pairwise parsing sidesteps this. - The whitelist check is deliberate. Python's
int(s, 16)accepts whitespace, signs, underscores and its own0xprefix, and methods likeisalnumaccept non-ASCII characters, so relying on them would wrongly accept some invalid inputs.
Complexity
- Time: O(n) for n <= 100 in the worst case (the prefix check and length check are constant, and at most 8 characters are scanned once the length matches), effectively constant.
- Space: O(1) beyond the input, apart from the short output string.
Reference solution
def hex_to_dotted_quad(text: str) -> str:
# Remove a single optional 0x / 0X prefix.
if text.startswith(("0x", "0X")):
text = text[2:]
# Exactly eight ASCII hex digits; explicit whitelist rejects whitespace,
# signs, underscores and non-ASCII digits.
allowed = "0123456789abcdefABCDEF"
if len(text) != 8 or any(c not in allowed for c in text):
return "INVALID"
# Network order: each pair of digits is the next octet (0..255).
octets = [str(int(text[i:i + 2], 16)) for i in range(0, 8, 2)]
return ".".join(octets)