KatInterview

Decode a Hex String into a Dotted-Quad Network Address

StringsAuto-graded · 28 test cases
MediumAuto-gradedStringsstringsparsingvalidation

Last 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 0x or 0X prefix. After that optional prefix is removed, exactly eight hexadecimal digits must remain.
  • Hexadecimal digits are 0-9, a-f and A-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 second 0x stays 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) <= 100
  • text is 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.