php 十六進位轉化為二進位的代碼

來源:互聯網
上載者:User
  1. var_dump(decto_bin(array(128,253),2));

  2. var_dump(decto_bin(array(128,253),8));
  3. var_dump(decto_bin(array(128,253),16));

  4. X-Powered-By: PHP/5.2.0

  5. Content-type: text/html

  6. array(2) {

  7. [0]=>
  8. string(8) "10000000"
  9. [1]=>
  10. string(8) "11111101"
  11. }
  12. array(2) {
  13. [0]=>
  14. string(4) "0200"
  15. [1]=>
  16. string(4) "0375"
  17. }
  18. array(2) {
  19. [0]=>
  20. string(2) "80"
  21. [1]=>
  22. string(2) "FD"
  23. }

複製代碼

2,二進位、八進位、十六進位轉十進位此轉換用乘法,如:1101 轉十進位:1*2^3+1*2^2+0*2^1+1*2^0

代碼:

0,'1'=>1,'2'=>2,'3'=>3,'4'=>4,'5'=>5,'6'=>6,'7'=>7,'8'=>8,'9'=>9,'A'=>10,'B'=>11,'C'=>12,'D'=>13,'E'=>14,'F'=>15);    if(!is_array($datalist))$datalist=array($datalist);    if($bin==10)return $datalist; //為10進位不轉換    $aOutData=array(); //定義輸出儲存數組    foreach ($datalist as $num)    {        $atnum=str_split($num); //將字串分割為單個字元數組        $atlen=count($atnum);        $total=0;        $i=1;        foreach ($atnum as $tv)        {            $tv=strtoupper($tv);                         if(array_key_exists($tv,$arr))            {                if($arr[$tv]==0)continue;                $total=$total+$arr[$tv]*pow($bin,$atlen-$i);            }            $i++;        }        $aOutData[]=$total;    }    return $aOutData;}?>

測試:

  1. var_dump(bin_todec(array('ff','ff33','cc33'),16));

  2. var_dump(bin_todec(array('1101101','111101101'),2));
  3. var_dump(bin_todec(array('1234123','12341'),8));

  4. X-Powered-By: PHP/5.2.0

  5. Content-type: text/html

  6. array(3) {

  7. [0]=>
  8. int(255)
  9. [1]=>
  10. int(65331)
  11. [2]=>
  12. int(52275)
  13. }
  14. array(2) {
  15. [0]=>
  16. int(124)
  17. [1]=>
  18. int(508)
  19. }
  20. array(2) {
  21. [0]=>
  22. int(342099)
  23. [1]=>
  24. int(5345)
  25. }

複製代碼

總結:在php中內建不少函數可以完成以上的進位轉換,比如bindec(),decoct(),dechex() base_convert() decbin()等。通過本文,帶給大家一個實現php中進位轉換的思路,希望對大家有所協助。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.