Hex Address to Dotted IPv4

Asked at Microsoft· Onsite

Reported by the problem's creator, not verified

Import another question

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.

Examples

  1. Example 1

    Input: text = C0A80101

    Output: 192.168.1.1

    Explanation: The pairs C0, A8, 01 and 01 are 192, 168, 1 and 1, read left to right.

  2. Example 2

    Input: text = 0xffffffff

    Output: 255.255.255.255

    Explanation: The 0x prefix is dropped and each ff pair is 255.

Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question

Code

Loading editor…

Ln 1, Col 1

Start an attempt to use Coach.