Reputation: 11
How can I convert the MAC address from "0013D5011F46" to "0.19.213.1.31.70" in PHP ? thanks!
Upvotes: 1
Views: 3157
Reputation: 882028
Here's one way to do it as a general purpose solution, being able to handle any length hex string:
<?php
function doNext($s, $slen) {
// String is even length here, exit if
// no sections left.
if ($slen == 0) {
return;
}
// This is a section other than the first,
// so prefix it with "." and output decimal.
echo ".";
echo hexdec(substr($s, 0, 2));
// Do remainder of string.
doNext(substr($s, 2), $slen - 2);
}
function doIt($s) {
// Get length, exit if zero.
$slen = strlen($s);
if ($slen == 0) {
return;
}
// Process forst section, one or two
// characters depending on length.
if (($slen % 2) != 0) {
echo hexdec(substr($s, 0, 1));
doNext(substr($s, 1), $slen - 1);
} else {
echo hexdec(substr($s, 0, 2));
doNext(substr($s, 2), $slen - 2);
}
}
// Here's the test case, feel free to expand.
doIt("0013D5011F46");
?>
It basically treats the string as a grouping of two-hex-digit sections, handling the front one (which may only be one character long if the string length is odd) then stripping that off and processing the rest of the string recursively.
For each section other than the first, it outputs the .
followed by the decimal value.
Upvotes: 2
Reputation: 940
Try this:
$str = '0013D5011F46';
$mac = implode('.', array_map('hexdec', str_split($str, 2)));
OR
$str = '00:13:D5:01:1F:46';
$hex = explode(':', $str);
$result = implode(array_map('hexdec', $hex), '.');
echo $result;
Upvotes: 2
Reputation: 2946
One-liner:
$mac = implode('.', array_map("hexdec", str_split("0013D5011F46", 2)));
Explanation:
$arr = str_split("0013D5011F46", 2); // split the string into chunks of two characters
$arr = array_map("hexdec", $arr); // convert every hex value to its decimal equivalent
$mac = implode('.', $arr); // join array elements to string
For reference see str_split()
, array_map()
, hexdec()
and implode()
Upvotes: 3
Reputation: 8372
$input = '0013D5011F46';
$output = implode(".", array_map( 'hexdec', explode( "\n", trim(chunk_split($input, 2)))));
0.19.213.1.31.70
Upvotes: 0