【问题标题】:How to convert MAC address from hex to decimal in php?如何在php中将MAC地址从十六进制转换为十进制?
【发布时间】:2017-04-23 09:52:59
【问题描述】:

如何在 PHP 中将 MAC 地址从“0013D5011F46”转换为“0.19.213.1.31.70”? 谢谢!

【问题讨论】:

标签: php hex decimal


【解决方案1】:

单线:

$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()

【讨论】:

    【解决方案2】:

    试试这个:

    $str = '0013D5011F46';
    $mac = implode('.', array_map('hexdec', str_split($str, 2)));
    

    $str = '00:13:D5:01:1F:46';
    $hex = explode(':', $str);
    $result = implode(array_map('hexdec', $hex), '.');
    echo $result;
    

    Working DEMO

    【讨论】:

      【解决方案3】:

      这是一种通用解决方案的一种方法,能够处理任何长度的十六进制字符串:

      <?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");
      ?>
      

      它基本上将字符串视为一组两位十六进制数字部分,处理前面的部分(如果字符串长度为奇数,则可能只有一个字符长),然后将其剥离并递归处理字符串的其余部分.

      对于除第一个部分之外的每个部分,它输出. 后跟十进制值。

      【讨论】:

        【解决方案4】:
        $input = '0013D5011F46';
        
        $output = implode(".", array_map( 'hexdec', explode( "\n", trim(chunk_split($input, 2)))));
        

        0.19.213.1.31.70

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-08-08
          • 1970-01-01
          • 1970-01-01
          • 2012-09-13
          • 1970-01-01
          • 2021-01-04
          • 1970-01-01
          • 2020-07-26
          相关资源
          最近更新 更多