如何从" 0013D5011F46"转换MAC地址?至" 0.19.213.1.31.70"用PHP? 谢谢!
答案 0 :(得分:3)
One-liner:
$mac = implode('.', array_map("hexdec", str_split("0013D5011F46", 2)));
说明:
$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
有关参考,请参阅str_split()
,array_map()
,hexdec()
和implode()
答案 1 :(得分:2)
试试这个:
$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;
答案 2 :(得分:2)
以下一种方式将其作为通用解决方案,能够处理任意长度的十六进制字符串:
<?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");
?>
它基本上将字符串视为一个由两个十六进制数字组成的分组,处理前一个(如果字符串长度为奇数,则可能只有一个字符长),然后将其剥离并递归处理字符串的其余部分
对于第一个以外的每个部分,它输出.
后跟十进制值。
答案 3 :(得分:0)
$input = '0013D5011F46';
$output = implode(".", array_map( 'hexdec', explode( "\n", trim(chunk_split($input, 2)))));
0.19.213.1.31.70