A-A+

php实现的任意进制互转类分享

2021年06月09日 我爱编程 暂无评论

这篇文章主要介绍了php实现的任意进制互转类分享,本文直接给出了实现代码,需要的朋友可以参考下。

之前不知道php自带有base_convert可以实现任意进制之间的转换,自己写了一个。。。。

  1. <?php
  2. /**
  3.  * 进制转换类 
  4.  * @author sgf@funcity
  5.  * @version 2011-02-15
  6.  */
  7. Class Hex{
  8.  private static $element = array(
  9.  '0','1','2','3','4','5','6','7','8','9',
  10.  'A','B','C','D','E','F','G','H','I','J',
  11.  'K','L','M','N','O','P','Q','R','S','T',
  12.  'U','V','W','X','Y','Z'
  13.  );
  14.  private static $hex_min = 2;
  15.  private static $hex_max = 36;
  16.  /**
  17.  * 进制转换
  18.  */
  19.  public function conv($int,$out_hex,$in_hex=10,$use_system=true){
  20.  if($use_system && function_exists('base_convert')){
  21.   return strtoupper(base_convert($int,$in_hex,$out_hex));
  22.  }
  23.  if($out_hex == $in_hex){
  24.   return $int;
  25.  }
  26.  if($out_hex > self::$hex_max || $out_hex < self::$hex_min){
  27.   return false;
  28.  }
  29.  if($in_hex > self::$hex_max || $in_hex < self::$hex_min){
  30.   return false;
  31.  }
  32.  $hex_10 = $this->_conv2hex10($int,$in_hex);
  33.  return strtoupper($this->_conv_hex($hex_10,$out_hex));
  34.  }
  35.  /**
  36.  * 将任意进制数字转为10进制数字
  37.  */
  38.  private function _conv2hex10($int,$in_hex){
  39.  $int = strtoupper(trim($int));
  40.  if($in_hex==10){
  41.   return $int;
  42.  }elseif$in_hex== 2 && function_exists('bindec')){
  43.   return bindec($int);
  44.  } elseif($in_hex== 16 && function_exists('hexdec')){
  45.   return hexdec($int);
  46.  } elseif($in_hex== 8 && function_exists('octdec')){
  47.   return octdec($int);
  48.  }
  49.  $array = array();
  50.  $result = 0;
  51.  for($i=0;$i<strlen($int);$i++){
  52.   array_unshift$arraysubstr($int,$i,1)); //插入到数组头部(既倒序)
  53.  }
  54.  foreach($array as $k => $v){
  55.   $hex10_value = array_search($v,self::$element);
  56.   if($hex10_value==-1){
  57.   return false;
  58.   }
  59.   $result += intval( pow($in_hex,$k) * $hex10_value );
  60.  }
  61.  return $result;
  62.  }
  63.  /**
  64.  * 把10进制数换成任意进制数
  65.  */
  66.  private function _conv_hex($hex_10,$out_hex){
  67.  $hex_10 = intval($hex_10);
  68.  if($out_hex==10){
  69.   return $hex_10;
  70.  }else if$out_hex==2  && function_exists('decbin')){
  71.   return decbin($hex_10);
  72.  } elseif ( $out_hex ==16 && function_exists('dechex')){
  73.   return dechex($hex_10);
  74.  } elseif ( $out_hex ==8 && function_exists('decoct')){
  75.   return decoct($hex_10);
  76.  }
  77.  $array = array();
  78.  $result = "";
  79.  //利用10进制数除任意进制数 倒取余数法转换。
  80.  do {
  81.   array_unshift$array$hex_10 % $out_hex); //余数插入到数组数组第1个位置。
  82.   $hex_10 = $hex_10 / $out_hex ; //除法
  83.  } while ($hex_10>1);
  84.  foreach($array as $k){
  85.   $result .= self::$element[$k];
  86.  }
  87.  return $result;
  88.  }
  89. }
  90. ?>

给我留言

Copyright © 四季博客 保留所有权利.   Theme  Ality

用户登录