Given a valid IPv4 address as a string, convert it to its IPv4-mapped IPv6 address representation.
An IPv4-mapped IPv6 address has the format ::ffff:xxxx:xxxx, where xxxx:xxxx is the IPv4 address expressed in hexadecimal. Each octet of the IPv4 address is converted to an integer, and the four octets are grouped into two 16-bit pairs: the first two octets form the first group and the last two octets form the second. Each pair is represented as a lowercase hexadecimal value without leading zeros, and the two groups are separated by a colon.
Return the full IPv4-mapped address string.
Function Signature
def ipv4_to_ipv6(ipv4: str) -> str:
Rules
-
The output always starts with the exact prefix
::ffff:
.
-
In each 16-bit group, the earlier octet is the high byte. The group value is
first * 256 + second
.
-
Write each group in lowercase hexadecimal with leading zeros removed. A group whose value is 0 is written as
0
.
Constraints
-
The input is always a valid IPv4 address.
-
Each octet is an integer between
0
and
255
.
-
The IPv4 address contains exactly 4 octets separated by dots.
Examples
Input: ipv4 = "192.168.1.1"
Output: "::ffff:c0a8:101"
192 is 0xc0 and 168 is 0xa8, so the first group is 0xc0a8, written c0a8. The last two octets are both 1, so the second group is 0x0101, written 101 once the leading zero is dropped.
Input: ipv4 = "0.0.0.0"
Output: "::ffff:0:0"
All octets are 0, so both 16-bit groups are 0x0000, and each is displayed as 0.
Input: ipv4 = "10.0.0.255"
Output: "::ffff:a00:ff"
The first group is 10 * 256 + 0 = 2560, which is 0x0a00 and is written a00. The second group is 0 * 256 + 255 = 255, which is 0x00ff and is written ff.