Exemple #1
0
 /**
  * Convert decimal number as a string to binary number
  * For TblUtil in Karate rank
  *
  * Example:
  * Input:  string $uuid = "465827479475458048";
  * Output: string 10101001111100111001111111100000110000000001000000000000
  *
  * @time 2015/08/30 21:45
  *
  * @param $uuid string
  * @param $base string The convert base
  * @return bool
  */
 public static function convertDecimal2Binary($uuid = "", $base = "2")
 {
     if (empty($uuid) || bccomp($uuid, "0", 0) <= 0) {
         return false;
     }
     $binaryResult = "";
     bcscale(0);
     //Set the default precision
     $intBase = (int) $base;
     while (true) {
         if (substr_compare($uuid, "0", 0) == 0) {
             break;
         }
         $last = substr($uuid, -1);
         //Get the last number
         $divFlag = 0;
         if ($last % $intBase == 0) {
             //If $uuid could be divisible
             $binaryResult .= "0";
         } else {
             $binaryResult .= "1";
             $divFlag = 1;
         }
         if ($divFlag == 1) {
             $lastTwo = substr($uuid, -2);
             $replace = (string) ((int) $lastTwo - 1);
             $uuid = substr_replace($uuid, $replace, -2);
         }
         $uuid = bcdiv($uuid, $base);
     }
     $binaryResult = strrev($binaryResult);
     //Reversing the binary sequence to get the right result
     return $binaryResult;
 }
Exemple #2
0
 /**
  * Generate a valid prime based on which php is used. Slower than the Prime generator.
  * @return \Generator
  */
 public static function generator()
 {
     $primes = ['2'];
     $currentNumber = '2';
     (yield '2');
     while (true) {
         ++$currentNumber;
         $unitNumber = (int) substr($currentNumber, -1);
         if (($currentNumber & 1) === 0) {
             continue;
         }
         $squareRoot = bcsqrt($currentNumber);
         $foundPrimeDivisor = false;
         foreach ($primes as $prime) {
             if (bccomp($prime, $squareRoot) === 1) {
                 break;
             }
             if (bcmod($currentNumber, $prime) === '0') {
                 $foundPrimeDivisor = true;
                 break;
             }
         }
         if (!$foundPrimeDivisor) {
             $primes[] = $currentNumber;
             (yield $currentNumber);
         }
     }
 }
 /**
  * 10进制转其它进制
  * 
  * @access public
  * @param String $dec 十进制数据
  * @param String $toRadix 要转换的进制
  * @return String
  */
 public static function dec2Any($dec, $toRadix)
 {
     $MIN_RADIX = 2;
     $MAX_RADIX = 62;
     $num62 = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
     if ($toRadix < $MIN_RADIX || $toRadix > $MAX_RADIX) {
         $toRadix = 2;
     }
     if ($toRadix == 10) {
         return $dec;
     }
     $buf = array();
     $charPos = 64;
     $isNegative = $dec < 0;
     if (!$isNegative) {
         $dec = -$dec;
     }
     while (bccomp($dec, -$toRadix) <= 0) {
         $buf[$charPos--] = $num62[-bcmod($dec, $toRadix)];
         $dec = bcdiv($dec, $toRadix);
     }
     $buf[$charPos] = $num62[-$dec];
     if ($isNegative) {
         $buf[--$charPos] = '-';
     }
     $_any = '';
     for ($i = $charPos; $i < 65; $i++) {
         $_any .= $buf[$i];
     }
     return $_any;
 }
 public function isLowerThan($decimal)
 {
     if (!$decimal instanceof Decimal) {
         $decimal = new Decimal($decimal);
     }
     return bccomp($this->amount, $decimal->getAmount(), self::$scale) === -1;
 }
Exemple #5
0
 function bcinvert($a, $n)
 {
     // Sanity check
     if (!is_scalar($a)) {
         user_error('bcinvert() expects parameter 1 to be string, ' . gettype($a) . ' given', E_USER_WARNING);
         return false;
     }
     if (!is_scalar($n)) {
         user_error('bcinvert() expects parameter 2 to be string, ' . gettype($n) . ' given', E_USER_WARNING);
         return false;
     }
     $u1 = $v2 = '1';
     $u2 = $v1 = '0';
     $u3 = $n;
     $v3 = $a;
     while (bccomp($v3, '0')) {
         $q0 = bcdiv($u3, $v3);
         $t1 = bcsub($u1, bcmul($q0, $v1));
         $t2 = bcsub($u2, bcmul($q0, $v2));
         $t3 = bcsub($u3, bcmul($q0, $v3));
         $u1 = $v1;
         $u2 = $v2;
         $u3 = $v3;
         $v1 = $t1;
         $v2 = $t2;
         $v3 = $t3;
     }
     if (bccomp($u2, '0') < 0) {
         return bcadd($u2, $n);
     } else {
         return bcmod($u2, $n);
     }
 }
Exemple #6
0
/**
 * Convert a large arbitrary number between arbitrary bases
 *
 * Works the same as the php version but supports large arbitrary numbers by using BCMath
 *
 * @see http://php.net/manual/en/function.base-convert.php
 * @see http://php.net/manual/en/function.base-convert.php#109660
 * @param string $number
 * @param int $frombase
 * @param int $tobase
 * @return string
 */
function base_convert($number, $frombase, $tobase)
{
    if ($frombase == $tobase) {
        return $number;
    }
    $number = trim($number);
    if ($frombase != 10) {
        $len = strlen($number);
        $fromDec = 0;
        for ($i = 0; $i < $len; $i++) {
            $v = \base_convert($number[$i], $frombase, 10);
            $fromDec = bcadd(bcmul($fromDec, $frombase, 0), $v, 0);
        }
    } else {
        $fromDec = $number;
    }
    if ($tobase != 10) {
        $result = '';
        while (bccomp($fromDec, '0', 0) > 0) {
            $v = intval(bcmod($fromDec, $tobase));
            $result = \base_convert($v, 10, $tobase) . $result;
            $fromDec = bcdiv($fromDec, $tobase, 0);
        }
    } else {
        $result = $fromDec;
    }
    return (string) $result;
}
 /**
  * Validate comma-separated IP address ranges.
  *
  * @param string $ranges
  *
  * @return bool
  */
 public function validate($ranges)
 {
     if (!is_string($ranges)) {
         $this->setError(_s('Invalid IP address range "%1$s": must be a string.', $this->stringify($ranges)));
         return false;
     }
     if ($ranges === '') {
         $this->setError(_('IP address range cannot be empty.'));
         return false;
     }
     $this->maxIPCount = 0;
     $this->maxIPRange = '';
     foreach (explode(',', $ranges) as $range) {
         $range = trim($range, " \t\r\n");
         if (!$this->isValidMask($range) && !$this->isValidRange($range)) {
             $this->setError(_s('Invalid IP address range "%1$s".', $range));
             return false;
         }
     }
     if ($this->ipRangeLimit != 0 && bccomp($this->maxIPCount, $this->ipRangeLimit) > 0) {
         $this->setError(_s('IP range "%1$s" exceeds "%2$s" address limit.', $this->maxIPRange, $this->ipRangeLimit));
         return false;
     }
     return true;
 }
 /**
  * @return Twig_SimpleFunction
  */
 public function formatAccountPerspective() : Twig_SimpleFunction
 {
     return new Twig_SimpleFunction('formatAccountPerspective', function (TransactionJournal $journal, Account $account) {
         $cache = new CacheProperties();
         $cache->addProperty('formatAccountPerspective');
         $cache->addProperty($journal->id);
         $cache->addProperty($account->id);
         if ($cache->has()) {
             return $cache->get();
         }
         // get the account amount:
         $transactions = $journal->transactions()->where('transactions.account_id', $account->id)->get(['transactions.*']);
         $amount = '0';
         foreach ($transactions as $transaction) {
             $amount = bcadd($amount, strval($transaction->amount));
         }
         if ($journal->isTransfer()) {
             $amount = bcmul($amount, '-1');
         }
         // check if this sum is the same as the journal:
         $journalSum = TransactionJournal::amount($journal);
         $full = Amount::formatJournal($journal);
         if (bccomp($journalSum, $amount) === 0 || bccomp(bcmul($journalSum, '-1'), $amount) === 0) {
             $cache->store($full);
             return $full;
         }
         $formatted = Amount::format($amount, true);
         if ($journal->isTransfer()) {
             $formatted = '<span class="text-info">' . Amount::format($amount) . '</span>';
         }
         $str = $formatted . ' (' . $full . ')';
         $cache->store($str);
         return $str;
     });
 }
 /**
  * @param $str string
  * @param $frombase int
  * @param $tobase int 
  *
  * @return string
  * 
  * Converts integers from base to another.
  */
 public static function baseConvert($str, $frombase = 10, $tobase = 36)
 {
     $str = trim($str);
     if (intval($frombase) != 10) {
         $len = strlen($str);
         $q = 0;
         for ($i = 0; $i < $len; $i++) {
             $r = base_convert($str[$i], $frombase, 10);
             $q = bcadd(bcmul($q, $frombase), $r);
         }
     } else {
         $q = $str;
     }
     if (intval($tobase) != 10) {
         $s = '';
         while (bccomp($q, '0', 0) > 0) {
             $r = intval(bcmod($q, $tobase));
             $s = base_convert($r, 10, $tobase) . $s;
             $q = bcdiv($q, $tobase, 0);
         }
     } else {
         $s = $q;
     }
     return $s;
 }
 public function testNull()
 {
     $oDB = new \LibPostgres\LibPostgresDriver(array('host' => getenv('TEST_HOST') ?: 'localhost', 'port' => getenv('TEST_PORT') ?: 5432, 'user_name' => getenv('TEST_USER_NAME'), 'user_password' => getenv('TEST_PASSWORD'), 'db_name' => getenv('TEST_DB_NAME')));
     // ?d
     $iFirst = 1;
     $iSecond = 2;
     $aResult = $oDB->selectRecord("\n            SELECT  (?d IS NULL)::integer AS is_null,\n                    (?d IS NOT NULL)::integer AS is_not_null,\n                    (SELECT sum(COALESCE(x, 0)) FROM unnest(array[?d]::integer[]) AS x) AS sum_coalesce\n        ", null, $iFirst, array($iFirst, null, $iSecond));
     $this->assertEquals(1, $aResult['is_null']);
     $this->assertEquals(1, $aResult['is_not_null']);
     $this->assertEquals($iFirst + $iSecond, $aResult['sum_coalesce']);
     // ?f
     $fFirst = 1.1;
     $fSecond = 2.2;
     $aResult = $oDB->selectRecord("\n            SELECT  (?f IS NULL)::integer AS is_null,\n                    (?f IS NOT NULL)::integer AS is_not_null,\n                    (SELECT sum(COALESCE(x, 0)) FROM unnest(array[?f]::numeric[]) AS x) AS sum_coalesce\n        ", null, $fFirst, array($fFirst, null, $fSecond));
     $this->assertEquals(1, $aResult['is_null']);
     $this->assertEquals(1, $aResult['is_not_null']);
     $this->assertTrue(bccomp($fFirst + $fSecond, $aResult['sum_coalesce'], 2) === 0);
     // ?j / ?jb / ?h
     $aResult = $oDB->selectRecord("\n            SELECT  (?j IS NULL)::integer AS is_j_null,\n                    (?jb IS NULL)::integer AS is_jb_null,\n                    (?h IS NULL)::integer AS is_h_null,\n                    ((?h->'i_am_null') IS NULL)::integer AS is_null_inside_hstore,\n                    ((?h->'i_am_not_null') IS NOT NULL)::integer AS is_not_null_inside_hstore\n        ", null, null, null, array('i_am_null' => null, 'i_am_not_null' => 1), array('i_am_null' => null, 'i_am_not_null' => 1));
     $this->assertEquals(1, $aResult['is_j_null']);
     $this->assertEquals(1, $aResult['is_jb_null']);
     $this->assertEquals(1, $aResult['is_jb_null']);
     $this->assertEquals(1, $aResult['is_null_inside_hstore']);
     $this->assertEquals(1, $aResult['is_not_null_inside_hstore']);
     // ?w
     $sString1 = null;
     $sString2 = "2'2\r";
     $sStringDefault = "3'3\n";
     $aResult = $oDB->selectRecord("\n            SELECT  (?w IS NULL)::integer AS is_null,\n                    (?w IS NOT NULL)::integer AS is_not_null,\n                    COALESCE(?w, ?w) || ?w AS concat,\n                    (SELECT string_agg(COALESCE(s, ?w), '') FROM unnest(array[?w]::varchar[]) AS s) AS concat_coalesce\n\n        ", $sString1, $sString2, $sString1, $sStringDefault, $sString2, $sStringDefault, array($sString1, $sString2, $sString1));
     $this->assertEquals(1, $aResult['is_null']);
     $this->assertEquals(1, $aResult['is_not_null']);
     $this->assertEquals($sStringDefault . $sString2, $aResult['concat']);
     $this->assertEquals($sStringDefault . $sString2 . $sStringDefault, $aResult['concat_coalesce']);
 }
function GetAuthID($i64friendID)
{
    $tmpfriendID = $i64friendID;
    $iServer = "1";
    if (extension_loaded('bcmath') == 1) {
        //decode communityid with bcmath
        if (bcmod($i64friendID, "2") == "0") {
            $iServer = "0";
        }
        $tmpfriendID = bcsub($tmpfriendID, $iServer);
        if (bccomp("76561197960265728", $tmpfriendID) == -1) {
            $tmpfriendID = bcsub($tmpfriendID, "76561197960265728");
        }
        $tmpfriendID = bcdiv($tmpfriendID, "2");
        return "STEAM_0:" . $iServer . ":" . $tmpfriendID;
    } else {
        if (extension_loaded('gmp') == 1) {
            //decode communityid with gmp
            if (gmp_mod($i64friendID, "2") == "0") {
                $iServer = "0";
            }
            $tmpfriendID = gmp_sub($tmpfriendID, $iServer);
            if (gmp_cmp("76561197960265728", $tmpfriendID) == -1) {
                $tmpfriendID = gmp_sub($tmpfriendID, "76561197960265728");
            }
            $tmpfriendID = gmp_div($tmpfriendID, "2");
            return "STEAM_0:" . $iServer . ":" . gmp_strval($tmpfriendID);
        }
    }
    return false;
}
Exemple #12
0
 public function onAfterOrderCreate(&$order)
 {
     if (empty($order) || empty($order->order_type) || $order->order_type != 'sale' || !isset($order->order_full_price)) {
         return;
     }
     $this->init();
     $send_confirmation = $this->params->get('send_confirmation', 1);
     if (!$send_confirmation && $order->order_status == 'confirmed') {
         $class = hikashop_get('class.cart');
         $class->cleanCartFromSession();
         return;
     }
     if ($send_confirmation && bccomp($order->order_full_price, 0, 5) == 0) {
         $config = hikashop_config();
         $orderObj = new stdClass();
         $orderObj->order_id = (int) $order->order_id;
         $orderObj->order_status = $config->get('order_confirmed_status', 'confirmed');
         $orderObj->history = new stdClass();
         $orderObj->history->history_notified = 1;
         $orderClass = hikashop_get('class.order');
         $orderClass->save($orderObj);
         $class = hikashop_get('class.cart');
         $class->cleanCartFromSession();
     }
 }
function pleac_Comparing_Floating_Point_Numbers()
{
    // In PHP floating point comparisions are 'safe' [meaning the '==' comparison operator
    // can be used] as long as the value consists of 14 digits or less [total digits, either
    // side of the decimal point e.g. xxxxxxx.xxxxxxx, xxxxxxxxxxxxxx., .xxxxxxxxxxxxxx]. If
    // values with more digits must be compared, then:
    //
    // * Represent as strings, and take care to avoid any implicit conversions e.g. don't pass
    //   a float as a float to a function and expect all digits to be retained - they won't be -
    //   then use 'strcmp' to compare the strings
    //
    // * Avoid float use; perhaps use arbitrary precision arithmetic. In this case, the
    //   'bccomp' function is relevant
    // Will work as long as each floating point value is 14 digits or less
    if ($float_1 == $float_2) {
        // ...
    }
    // Compare as strings
    $cmp = strcmp('123456789.123456789123456789', '123456789.123456789123456788');
    // Use 'bccomp'
    $precision = 5;
    // Number of significant comparison digits after decimal point
    if (bccomp('1.111117', '1.111116', $precision)) {
        // ...
    }
    $precision = 6;
    if (bccomp('1.111117', '1.111116', $precision)) {
        // ...
    }
    // ----------------------------
    $wage = 536;
    $week = $wage * 40;
    printf("One week's wage is: \$%.2f\n", $week / 100);
}
/**
 * Replace bcpowmod()
 *
 * @category    PHP
 * @package     PHP_Compat
 * @license     LGPL - http://www.gnu.org/licenses/lgpl.html
 * @copyright   2004-2007 Aidan Lister <aidan@php.net>, Arpad Ray <arpad@php.net>
 * @link        http://php.net/function.bcpowmod
 * @author      Sara Golemon <pollita@php.net>
 * @version     $Revision: 1.1 $
 * @since       PHP 5.0.0
 * @require     PHP 4.0.0 (user_error)
 */
function php_compat_bcpowmod($x, $y, $modulus, $scale = 0)
{
    // Sanity check
    if (!is_scalar($x)) {
        user_error('bcpowmod() expects parameter 1 to be string, ' . gettype($x) . ' given', E_USER_WARNING);
        return false;
    }
    if (!is_scalar($y)) {
        user_error('bcpowmod() expects parameter 2 to be string, ' . gettype($y) . ' given', E_USER_WARNING);
        return false;
    }
    if (!is_scalar($modulus)) {
        user_error('bcpowmod() expects parameter 3 to be string, ' . gettype($modulus) . ' given', E_USER_WARNING);
        return false;
    }
    if (!is_scalar($scale)) {
        user_error('bcpowmod() expects parameter 4 to be integer, ' . gettype($scale) . ' given', E_USER_WARNING);
        return false;
    }
    $t = '1';
    while (bccomp($y, '0')) {
        if (bccomp(bcmod($y, '2'), '0')) {
            $t = bcmod(bcmul($t, $x), $modulus);
            $y = bcsub($y, '1');
        }
        $x = bcmod(bcmul($x, $x), $modulus);
        $y = bcdiv($y, '2');
    }
    return $t;
}
Exemple #15
0
function updateRegexp(array $regexp, array $expressions)
{
    try {
        $regexpId = $regexp['regexpid'];
        unset($regexp['regexpid']);
        // check existence
        if (!getRegexp($regexpId)) {
            throw new Exception(_('Regular expression does not exist.'));
        }
        // check required fields
        $dbFields = array('name' => null);
        if (!check_db_fields($dbFields, $regexp)) {
            throw new Exception(_('Incorrect arguments passed to function') . ' [updateRegexp]');
        }
        // check duplicate name
        $dbRegexp = DBfetch(DBselect('SELECT re.regexpid' . ' FROM regexps re' . ' WHERE re.name=' . zbx_dbstr($regexp['name']) . andDbNode('re.regexpid')));
        if ($dbRegexp && bccomp($regexpId, $dbRegexp['regexpid']) != 0) {
            throw new Exception(_s('Regular expression "%s" already exists.', $regexp['name']));
        }
        rewriteRegexpExpressions($regexpId, $expressions);
        DB::update('regexps', array('values' => $regexp, 'where' => array('regexpid' => $regexpId)));
    } catch (Exception $e) {
        error($e->getMessage());
        return false;
    }
    return true;
}
Exemple #16
0
 public function isZero(array $args)
 {
     $this->requireExactly(1, $args);
     $a = $args[0];
     $isZero = ($a instanceof Scheme_Int || $a instanceof Scheme_Float) && bccomp($a->value, "0") === 0;
     return new Scheme_Bool($isZero);
 }
Exemple #17
0
 public static function checkAddress($address)
 {
     $origbase58 = $address;
     $dec = "0";
     for ($i = 0; $i < strlen($address); $i++) {
         $dec = bcadd(bcmul($dec, "58", 0), strpos("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz", substr($address, $i, 1)), 0);
     }
     $address = "";
     while (bccomp($dec, 0) == 1) {
         $dv = bcdiv($dec, "16", 0);
         $rem = (int) bcmod($dec, "16");
         $dec = $dv;
         $address = $address . substr("0123456789ABCDEF", $rem, 1);
     }
     $address = strrev($address);
     for ($i = 0; $i < strlen($origbase58) && substr($origbase58, $i, 1) == "1"; $i++) {
         $address = "00" . $address;
     }
     if (strlen($address) % 2 != 0) {
         $address = "0" . $address;
     }
     if (strlen($address) != 50) {
         return false;
     }
     if (hexdec(substr($address, 0, 2)) > 0) {
         return false;
     }
     return substr(strtoupper(hash("sha256", hash("sha256", pack("H*", substr($address, 0, strlen($address) - 8)), true))), 0, 8) == substr($address, strlen($address) - 8);
 }
Exemple #18
0
 private function pow_mod($p, $q, $r)
 {
     $factors = array();
     $div = $q;
     $power_of_two = 0;
     while (bccomp($div, "0") == 1) {
         $rem = bcmod($div, 2);
         $div = bcdiv($div, 2);
         if ($rem) {
             array_push($factors, $power_of_two);
         }
         $power_of_two++;
     }
     $partial_results = array();
     $part_res = $p;
     $idx = 0;
     foreach ($factors as $factor) {
         while ($idx < $factor) {
             $part_res = bcpow($part_res, "2");
             $part_res = bcmod($part_res, $r);
             $idx++;
         }
         array_push($partial_results, $part_res);
     }
     $result = "1";
     foreach ($partial_results as $part_res) {
         $result = bcmul($result, $part_res);
         $result = bcmod($result, $r);
     }
     return $result;
 }
 protected static function decodeAddress($data)
 {
     $charsetHex = '0123456789ABCDEF';
     $charsetB58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
     $raw = "0";
     for ($i = 0; $i < strlen($data); $i++) {
         $current = (string) strpos($charsetB58, $data[$i]);
         $raw = (string) bcmul($raw, "58", 0);
         $raw = (string) bcadd($raw, $current, 0);
     }
     $hex = "";
     while (bccomp($raw, 0) == 1) {
         $dv = (string) bcdiv($raw, "16", 0);
         $rem = (int) bcmod($raw, "16");
         $raw = $dv;
         $hex = $hex . $charsetHex[$rem];
     }
     $withPadding = strrev($hex);
     for ($i = 0; $i < strlen($data) && $data[$i] == "1"; $i++) {
         $withPadding = "00" . $withPadding;
     }
     if (strlen($withPadding) % 2 != 0) {
         $withPadding = "0" . $withPadding;
     }
     return $withPadding;
 }
 /**
  * takes a simple list of item ids and pushes those items to the top of the list
  * starting with the first item id. doesn't need to be every item in the inventory.
  * just the ones you want sorted to the top of the list.
  * makes sense from an api standpoint but may not be perfect from an app standpoint.
  */
 public function sort(array $item_ids)
 {
     if (count($item_ids) < 1) {
         return FALSE;
     }
     rsort($item_ids);
     $user_id = $this->user();
     $pos = $this->maxPos();
     $min = $this->minCustomPos();
     if (bccomp($pos, $min) < 0) {
         $pos = $min;
     }
     if ($this->cacher) {
         $timeout = $this->cacheTimeout();
         foreach ($item_ids as $item_id) {
             $pos = bcadd($pos, 1);
             $this->cacher->set($item_id, $pos, 0, $timeout);
             if ($this->inTran()) {
                 Transaction::onRollback(array($this->cacher, 'delete'), array($item_id));
             }
         }
     }
     try {
         $this->storage('sorter')->sort($pos, $item_ids);
     } catch (Exception $e) {
         throw $this->handle($e);
     }
     return TRUE;
 }
Exemple #21
0
function powmod($base, $exponent, $modulus)
{
    if (function_exists('gmp_powm')) {
        // fast
        return gmp_strval(gmp_powm($base, $exponent, $modulus));
    }
    if (function_exists('bi_powmod')) {
        // not tested
        return bi_sto_str(bi_powmod($base, $exponent, $modulus));
    }
    if (function_exists('bcpowmod')) {
        // slow
        return bcpowmod($base, $exponent, $modulus);
    }
    // emulation, slow
    $square = bcmod($base, $modulus);
    $result = 1;
    while (bccomp($exponent, 0) > 0) {
        if (bcmod($exponent, 2)) {
            $result = bcmod(bcmul($result, $square), $modulus);
        }
        $square = bcmod(bcmul($square, $square), $modulus);
        $exponent = bcdiv($exponent, 2);
    }
    return $result;
}
Exemple #22
0
 private function ensureIsNotNegative($numberOfBytes)
 {
     if (bccomp($numberOfBytes, 0) < 0) {
         throw new NegativeBytesException();
     }
     return $numberOfBytes;
 }
 /** Return a timeout spec */
 function preSelect($prev = null)
 {
     if ($prev === false) {
         // Don't override previous handlers if they want to exit.
         return false;
     }
     list($uSecs, $epoch) = explode(' ', microtime());
     $epDiff = bccomp($epoch, $this->epoch);
     if ($epDiff == 1) {
         //$epoch is bigger
         return false;
     }
     $uSecs = bcmul($uSecs, '1000000');
     if ($epDiff == 0 && bccomp($uSecs, $this->usecs) >= 0) {
         // $usecs is bigger
         return false;
     }
     // Calculate select blockout values that expire at the same as the target exit time
     $udiff = bcsub($this->usecs, $uSecs);
     if (substr($udiff, 0, 1) == '-') {
         $blockTmSecs = (int) bcsub($this->epoch, $epoch) - 1;
         $udiff = bcadd($udiff, '1000000');
     } else {
         $blockTmSecs = (int) bcsub($this->epoch, $epoch);
     }
     // Return the nearest timeout.
     if (is_array($prev) && ($prev[0] < $blockTmSecs || $prev[0] == $blockTmSecs && $prev[1] < $udiff)) {
         return $prev;
     } else {
         return array($blockTmSecs, $udiff);
     }
 }
Exemple #24
0
 /**
  * Calculates the absolute value of a BCMath number.
  *
  * @param string $number a BCMath number string
  * @return string the absolute value
  */
 public static function bcabs($number)
 {
     assert(is_string($number));
     if (bccomp($number, '0') === -1) {
         return bcmul($number, '-1');
     }
     return $number;
 }
Exemple #25
0
 /**
  * Creates a new long long (-2^63 - (2^63)- 1)
  *
  * @param  string|double|int $initial
  */
 public function __construct($initial)
 {
     $initial = (string) $initial;
     if (-1 === bccomp($initial, '-9223372036854775808') || 1 === bccomp($initial, '9223372036854775807')) {
         throw new IllegalArgumentException('Out of range for an int64: ' . $initial);
     }
     $this->wrapped = bcadd($initial, 0);
 }
Exemple #26
0
 public function testRand()
 {
     $math = new Zend_Crypt_Math();
     $higher = '155172898181473697471232257763715539915724801966915404479707795314057629378541917580651227423698188993727816152646631438561595825688188889951272158842675419950341258706556549803580104870537681476726513255747040765857479291291572334510643245094715007229621094194349783925984760375594985848253359305585439638443';
     $lower = '155172898181473697471232257763715539915724801966915404479707795314057629378541917580651227423698188993727816152646631438561595825688188889951272158842675419950341258706556549803580104870537681476726513255747040765857479291291572334510643245094715007229621094194349783925984760375594985848253359305585439638442';
     $result = $math->rand($lower, $higher);
     $this->assertTrue(bccomp($result, $higher) !== '1');
     $this->assertTrue(bccomp($result, $lower) !== '-1');
 }
 /**
  * Convert to number
  *
  * @param   string n
  * @param   int scale
  * @param   int prec
  * @return  var
  */
 protected function toNumber($n, $scale, $prec)
 {
     if (0 === $scale) {
         return bccomp($n, PHP_INT_MAX) == 1 || bccomp($n, -PHP_INT_MAX - 1) == -1 ? $n : (int) $n;
     } else {
         $n = bcdiv($n, pow(10, $scale), $scale);
         return strlen($n) > self::$precision ? $n : (double) $n;
     }
 }
Exemple #28
0
function CalculaFatorial($Numero)
{
    $Parcial = '1';
    while (bccomp($Numero, '1') == 1) {
        $Parcial = bcmul($Numero, $Parcial);
        $Numero = bcsub($Numero, '1');
    }
    echo $Parcial . "<br>";
}
Exemple #29
0
/**
 * Convert an arbitrarily-long string from one numeric base to
 * another, optionally zero-padding to a minimum column width.
 *
 * Supports base 2 through 36; digit values 10-36 are represented
 * as lowercase letters a-z. Input is case-insensitive.
 *
 * @param string $input Input number
 * @param int $sourceBase Base of the input number
 * @param int $destBase Desired base of the output
 * @param int $pad Minimum number of digits in the output (pad with zeroes)
 * @param bool $lowercase Whether to output in lowercase or uppercase
 * @param string $engine Either "gmp", "bcmath", or "php"
 * @return string|bool The output number as a string, or false on error
 */
function base_convert($input, $sourceBase, $destBase, $pad = 1, $lowercase = true, $engine = 'auto')
{
    $input = (string) $input;
    if ($sourceBase < 2 || $sourceBase > 36 || $destBase < 2 || $destBase > 36 || $sourceBase != (int) $sourceBase || $destBase != (int) $destBase || $pad != (int) $pad || !preg_match("/^[" . substr('0123456789abcdefghijklmnopqrstuvwxyz', 0, $sourceBase) . "]+\$/i", $input)) {
        return false;
    }
    static $baseChars = array(10 => 'a', 11 => 'b', 12 => 'c', 13 => 'd', 14 => 'e', 15 => 'f', 16 => 'g', 17 => 'h', 18 => 'i', 19 => 'j', 20 => 'k', 21 => 'l', 22 => 'm', 23 => 'n', 24 => 'o', 25 => 'p', 26 => 'q', 27 => 'r', 28 => 's', 29 => 't', 30 => 'u', 31 => 'v', 32 => 'w', 33 => 'x', 34 => 'y', 35 => 'z', '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, 'g' => 16, 'h' => 17, 'i' => 18, 'j' => 19, 'k' => 20, 'l' => 21, 'm' => 22, 'n' => 23, 'o' => 24, 'p' => 25, 'q' => 26, 'r' => 27, 's' => 28, 't' => 29, 'u' => 30, 'v' => 31, 'w' => 32, 'x' => 33, 'y' => 34, 'z' => 35);
    if (extension_loaded('gmp') && ($engine == 'auto' || $engine == 'gmp')) {
        // Removing leading zeros works around broken base detection code in
        // some PHP versions (see <https://bugs.php.net/bug.php?id=50175> and
        // <https://bugs.php.net/bug.php?id=55398>).
        $result = gmp_strval(gmp_init(ltrim($input, '0') ?: '0', $sourceBase), $destBase);
    } elseif (extension_loaded('bcmath') && ($engine == 'auto' || $engine == 'bcmath')) {
        $decimal = '0';
        foreach (str_split(strtolower($input)) as $char) {
            $decimal = bcmul($decimal, $sourceBase);
            $decimal = bcadd($decimal, $baseChars[$char]);
        }
        // @codingStandardsIgnoreStart Generic.CodeAnalysis.ForLoopWithTestFunctionCall.NotAllowed
        for ($result = ''; bccomp($decimal, 0); $decimal = bcdiv($decimal, $destBase, 0)) {
            $result .= $baseChars[bcmod($decimal, $destBase)];
        }
        // @codingStandardsIgnoreEnd
        $result = strrev($result);
    } else {
        $inDigits = array();
        foreach (str_split(strtolower($input)) as $char) {
            $inDigits[] = $baseChars[$char];
        }
        // Iterate over the input, modulo-ing out an output digit
        // at a time until input is gone.
        $result = '';
        while ($inDigits) {
            $work = 0;
            $workDigits = array();
            // Long division...
            foreach ($inDigits as $digit) {
                $work *= $sourceBase;
                $work += $digit;
                if ($workDigits || $work >= $destBase) {
                    $workDigits[] = (int) ($work / $destBase);
                }
                $work %= $destBase;
            }
            // All that division leaves us with a remainder,
            // which is conveniently our next output digit.
            $result .= $baseChars[$work];
            // And we continue!
            $inDigits = $workDigits;
        }
        $result = strrev($result);
    }
    if (!$lowercase) {
        $result = strtoupper($result);
    }
    return str_pad($result, $pad, '0', STR_PAD_LEFT);
}
Exemple #30
0
function int2bin($num)
{
    $result = '';
    do {
        $result .= chr(bcmod($num, 256));
        $num = bcdiv($num, 256);
    } while (bccomp($num, 0));
    return $result;
}