开发者

What is an alternative to php function bcpow?

I'm using this guide - h开发者_Go百科ttp://kevin.vanzonneveld.net/techblog/article/create_short_ids_with_php_like_youtube_or_tinyurl/

to generate short codes for URL.

But bcpow() isn't working anyhow on my system.

I'm using php-cli and phpinfo(); shows bcmath is installed.

Numeric to shortcode -

function aplhaIdCalc( $in ) {
    $index = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";        
    $base = 62;
    $out = "";
    for ($t = floor(log($in, $base)); $t >= 0; $t--) {
      $bcp = bcpow($base, $t);
      $a   = floor($in / $bcp) % $base;
      $out = $out . substr($index, $a, 1);
      $in  = $in - ($a * $bcp);
    }
    $out = strrev($out); // reverse
    return $out;
}

Shortcode to numeric -

function idAlphaCalc( $in ) {
    $index = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";        
    $base = 62;
    $in  = strrev($in);
    $out = 0;
    $len = strlen($in) - 1;
    for ($t = 0; $t <= $len; $t++) {
      $bcpow = bcpow($base, $len - $t);
      $out   = $out + strpos($index, substr($in, $t, 1)) * $bcpow;
    }
    $out = sprintf('%F', $out);
    $out = substr($out, 0, strpos($out, '.'));
    return $out;
}

How can I use these functions without bcpow and yet get similar output and input?

I can't understand these BCMath functions but I think base_convert might work.

Edit : Changing bcpow to pow works. What are the risks involved in using pow ?


Diference between Math-Functions and BC Math-Functions:

  • Math: These math functions will only handle values within the range of the integer and float types on your computer
  • BC Math: For arbitrary precision mathematics PHP offers the Binary Calculator which supports numbers of any size and precision, represented as strings.

So precision is the answer.

Sure bcmath is loaded? Testet your functions on my local environment. no problem at all.

And you got a typo in your first function aplhaIdCalc => alphaIdCalc


Should the bcmath extension be non-functional, then you could resort to exec:

$pow = `echo '135^71' | bc`;

Take care to escapeshellcmd the numbers anyway. However this is a pretty slow workaround if done in a loop.


Turns out I was using wrong php path. The one with bcmath installed was /usr/local/lib/php and I was using /usr/bin/php in shebang.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜