產生短連結,php5.6可用,為什麼php7產生不了?

來源:互聯網
上載者:User
function shortUrl($long_url){    $key = '123';    $base32 = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";    // 利用md5演算法方式產生hash值    $hex = hash('md5', $long_url.$key);    $hexLen = strlen($hex);    $subHexLen = $hexLen / 8;    $output = array();    for($i=0;$i<$subHexLen;$i++){        // 將這32位分成四份,每一份8個字元,將其視作16進位串與0x3fffffff(30位1)與操作        $subHex = substr($hex, $i*8, 8);        $idx = 0x3FFFFFFF & (1 * ('0x' . $subHex));        // 這30位分成6段, 每5個一組,算出其整數值,然後映射到我們準備的62個字元        $out = '';        for($j=0;$j<6;$j++){            $val = $idx & 0x0000003D;            $out .= $base32[$val];            $idx = $idx >> 5;        }        $output[$i] = $out;    }    // 產生位元    return $output;}print_r( shortUrl('http://www.google.com/') );

php5.6輸出結果為:

Array(    [0] => MVvIZz    [1] => qURRjy    [2] => U7rIzu    [3] => JNNJbi)

php7輸出結果為:

Array(    [0] => aaaaaa    [1] => aaaaaa    [2] => aaaaaa    [3] => aaaaaa)

這是哪的問題?

回複內容:

function shortUrl($long_url){    $key = '123';    $base32 = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";    // 利用md5演算法方式產生hash值    $hex = hash('md5', $long_url.$key);    $hexLen = strlen($hex);    $subHexLen = $hexLen / 8;    $output = array();    for($i=0;$i<$subHexLen;$i++){        // 將這32位分成四份,每一份8個字元,將其視作16進位串與0x3fffffff(30位1)與操作        $subHex = substr($hex, $i*8, 8);        $idx = 0x3FFFFFFF & (1 * ('0x' . $subHex));        // 這30位分成6段, 每5個一組,算出其整數值,然後映射到我們準備的62個字元        $out = '';        for($j=0;$j<6;$j++){            $val = $idx & 0x0000003D;            $out .= $base32[$val];            $idx = $idx >> 5;        }        $output[$i] = $out;    }    // 產生位元    return $output;}print_r( shortUrl('http://www.google.com/') );

php5.6輸出結果為:

Array(    [0] => MVvIZz    [1] => qURRjy    [2] => U7rIzu    [3] => JNNJbi)

php7輸出結果為:

Array(    [0] => aaaaaa    [1] => aaaaaa    [2] => aaaaaa    [3] => aaaaaa)

這是哪的問題?

問題主要出現在這句話上
$idx = 0x3FFFFFFF & (1 * ('0x' . $subHex));
因為在php7中,十六進位的字串不再被認為是數字,所以這裡所採用的隱式轉換變成了無效轉換,導致結果出現了問題。
可以將此句替換為
$idx = 0x3FFFFFFF & hexdec($subHex);

  • 相關文章

    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.