Coding questions · Microsoft
Convert a Hexadecimal Address to Dotted IPv4
Convert an eight-digit hexadecimal address to network-order dotted IPv4 with strict validation, optional prefixes, and correct high-bit handling.
Convert a 32-bit hexadecimal address to dotted-decimal IPv4 notation.
Implement hex_to_ipv4(text: string) -> string.
Constraints & Assumptions
The source reports a hex-to-IPv4 conversion without exact formatting rules. This practice contract uses network-order bytes: the leftmost byte is the first decimal octet.
- Input length is at most 100. Accept exactly eight hexadecimal digits, optionally preceded by
0xor0X. - Hexadecimal digits are case-insensitive. Whitespace, signs, separators, and any other length or character are invalid.
- On valid input return four decimal octets separated by dots, without leading zeroes. On invalid input return
INVALID. - Treat the value as an unsigned 32-bit bit pattern; addresses whose high bit is set are valid.
Examples
hex_to_ipv4("C0A80101") -> "192.168.1.1"
hex_to_ipv4("0xffffffff") -> "255.255.255.255"
hex_to_ipv4("00000000") -> "0.0.0.0"
hex_to_ipv4("1FF") -> "INVALID"
Explain how your byte-order choice and signed-integer handling affect the result. A solution that parses four two-character byte values can avoid signed 32-bit overflow entirely.
Convert a Hexadecimal Address to Dotted IPv4
Approach
First recognize an optional exact 0x or 0X prefix. The remaining length must be exactly eight, and every character must belong to the ASCII hexadecimal alphabet. This rejects whitespace, signs, separators and permissive numeric-parser variants before parsing. Parse each consecutive two-character byte separately, left to right, then join its decimal value with dots. Each parsed value lies in [0,255], so no signed 32-bit overflow is possible. The four byte positions are preserved, establishing network order. Decimal conversion eliminates leading zeroes. Only eight digits are examined after the length check, so processing and auxiliary storage are constant under this fixed-width contract (excluding any language-level copy of the input).
- Time complexity: O(1) under the fixed eight-digit contract
- Space complexity: O(1) auxiliary space