首页 > 开发 > PHP > 正文

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

2024-05-04 23:37:23
字体:
来源:转载
供稿:网友

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

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

 

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

发表评论 共有0条评论
用户名: 密码:
验证码: 匿名发表