Usually, the IP address format we see is a dotted decimal format similar to 192.168.1.1 . But sometimes, the IP address is represented as a continuous hexadecimal string, for example:
C0A80101
This is actually a hexadecimal expression of 192.168.1.1 .
Every two hexadecimal number represents one byte (8 bits) in the IP address, for example:
C0 = 192
A8 = 168
01 = 1
01 = 1
PHP's built-in hexdec function can convert hex strings to decimal numbers. But it should be noted that it converts the overall number and cannot be used directly to convert the hexadecimal IP address in four segments. Therefore, we need to split the hexadecimal string in two bits first, and then convert it into a decimal number.
The following script shows how to convert a continuous 8-bit hexadecimal IP address into dotted decimal format using PHP:
<?php
function hexIpToDecimal($hexIp) {
// Convert the entered string to uppercase,Ensure a unified format
$hexIp = strtoupper($hexIp);
// Check if the length is correct(IPv4 yes 8 Hexadecimal)
if (strlen($hexIp) !== 8) {
return false; // Input format error
}
$ipParts = [];
// One group for every two,Convert to decimal
for ($i = 0; $i < 8; $i += 2) {
$partHex = substr($hexIp, $i, 2);
$partDec = hexdec($partHex);
$ipParts[] = $partDec;
}
// Spliced into dotted format
$decimalIp = implode('.', $ipParts);
return $decimalIp;
}
// Test Example
$hexIp = "C0A80101";
$decimalIp = hexIpToDecimal($hexIp);
echo "hexadecimalIP: $hexIp After conversion to: $decimalIp\n";
?>
Running results:
hexadecimalIP: C0A80101 After conversion to: 192.168.1.1
Input check <br> The function first ensures that the passed hexadecimal string is 8 bits long (corresponding to 4 bytes of IPv4).
Segmented processing <br> Use substr to take two characters at a time to represent one byte.
Convert hexadecimal to decimal <br> Use the hexdec function to convert a two-digit hex string to a decimal number.
Format splicing <br> Connect the converted four decimal numbers with dot numbers to generate common dotted decimal IP addresses.
If the hexadecimal IP address you encounter is delimited, such as C0:A8:01:01 , you can remove the delimiter first and then use the above method to deal with it:
$hexIp = str_replace(':', '', 'C0:A8:01:01');
$decimalIp = hexIpToDecimal($hexIp);
echo $decimalIp; // Output:192.168.1.1
Through the above method, using PHP's hexdec function, you can easily convert the IP address represented in hexadecimal into the familiar decimal dot-part format. Hope this article helps you!