duangong1979 2013-09-17 06:28
浏览 55
已采纳

php正在将base 16转换为base 2

Why am I getting this output from my function?

echo $var = hash_hmac('ripemd160', 'http://www.weburlhere.org', 0, 0);
echo "
";
echo $converted = base_convert($var, 16, 2);
echo "
";

Outputs:

407a9d8868a678e12d9fc0264f9ae11e8761b557
0000000000000000000000000000000000000000000000000000000000000000

Whereas base_convert($var, 16, 10) outputs

1421821959848150668406846884086820088622688484226 correctly.

Also, as a side-question (bonus points for this!) I'm assuming ripemd160 gives me a unique identifier for each input preimage. I'm attempting to make a url-shortening service that shortens a URL from any length to its hash digest (I'm assuming converting the binary to base64 with base64_encode($converted) will shorten the URL even more). Is this correct, and is this a good idea?

  • 写回答

2条回答 默认 最新

  • dongzongzi0379 2013-09-17 06:41
    关注

    The PHP document on base_convert said

    base_convert() may lose precision on large numbers due to properties related to the internal "double" or "float" type used. Please see the Floating point numbers section in the manual for more specific information and limitations.

    So, you cannot rely on this function to convert a large numbers. However, it is very easy manually write a function to convert from base 16 to base 2.

    function hex2bin($hex) {
        $table = array('0000', '0001', '0010', '0011', 
                       '0100', '0101', '0110', '0111',
                       '1000', '1001', '1010', 'a' => '1011', 
                       'b' => '1100', 'c' => '1101', 'e' => '1110', 
                       'f' => '1111');
        $bin = '';
    
        for($i = 0; $i < strlen($hex); $i++) {
            $bin .= $table[strtolower(substr($hex, $i, 1))];
        }
    
        return $bin;
    }
    echo hex2bin('407a9d8868a678e12d9fc0264f9ae11e8761b557');
    

    I'm assuming converting the binary to base64 with base64_encode($converted) will shorten the URL even more). Is this correct, and is this a good idea

    Yes, it is shorter. It is 32 times shorter than binary, and 4 times shorter than base-16. However, ripemd160 does not guarantee to give an unique identifier for every link. There are still some collisions (which I don't even know how rare it will be).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程