Hex Address to Dotted IPv4
MicrosoftOnsiteEasy
Network tools often print a 32-bit address as hexadecimal text. Implement hex_to_ipv4, which turns that text into dotted-decimal IPv4 notation, or returns the string INVALID when the text is not in the accepted format.
The accepted format is exactly eight hexadecimal digits (0-9, a-f, A-F, ASCII only), optionally preceded by 0x or 0X. Anything else is INVALID: surrounding whitespace, signs, separators, other digits and any other length. Every byte of the address is written as two digits and the leftmost byte is the first octet. All 32-bit patterns are valid, including those whose first bit is set. The output has four decimal octets joined by dots with no leading zeros. Each test is a single call.
Part 1: Hex to dotted decimal
Given a string text, return its dotted-decimal IPv4 form, or the string INVALID when text is not in the accepted format.
The accepted format is exactly eight hexadecimal digits (0-9, a-f, A-F), optionally preceded by 0x or 0X. Anything else is INVALID: whitespace, signs, separators, other characters, or a different length.
Each pair of digits is one octet, read left to right, so the leftmost pair is the first octet. All 32-bit values are valid, including values with the top bit set. The output is four decimal octets joined by dots, with no leading zeros.
- Example 1
- text
"C0A80101"- Output
"192.168.1.1"
Why: The pairs
C0,A8,01and01are 192, 168, 1 and 1, read left to right. - Example 2
- text
"0xffffffff"- Output
"255.255.255.255"
Why: The
0xprefix is dropped and eachffpair is 255.
Constraints
0 <= len(text) <= 100