0 if leftOperand is greater than rightOperand, and 0 if they are equal. * * @param string $leftOperand * @param string $rightOperand * @return int */ public function comp($leftOperand, $rightOperand) { return gmp_cmp($leftOperand, $rightOperand); } /** * Convert big integer into it's binary number representation * * @param string $int * @param bool $twoc return in twos' complement form * @return string */ public function intToBin($int, $twoc = false) { $nb = chr(0); $isNegative = (strpos($int, '-') === 0); $int = ltrim($int, '+-0'); if (empty($int)) { return $nb; } if ($isNegative && $twoc) { $int = gmp_sub($int, '1'); } $hex = gmp_strval($int, 16); if (strlen($hex) & 1) { $hex = '0' . $hex; } $bytes = pack('H*', $hex); $bytes = ltrim($bytes, $nb); if ($twoc) { if (ord($bytes[0]) & 0x80) { $bytes = $nb . $bytes; } return $isNegative ? ~$bytes : $bytes; } return $bytes; } /** * Convert binary number into big integer * * @param string $bytes * @param bool $twoc whether binary number is in twos' complement form * @return string */ public function binToInt($bytes, $twoc = false) { $isNegative = ((ord($bytes[0]) & 0x80) && $twoc); $sign = ''; if ($isNegative) { $bytes = ~$bytes; $sign = '-'; } $result = gmp_init($sign . bin2hex($bytes), 16); if ($isNegative) { $result = gmp_sub($result, '1'); } return gmp_strval($result); } /** * Base conversion. Bases 2..62 are supported * * @param string $operand * @param int $fromBase * @param int $toBase * @return string * @throws Exception\InvalidArgumentException */ public function baseConvert($operand, $fromBase, $toBase = 10) { if ($fromBase == $toBase) { return $operand; } if ($fromBase < 2 || $fromBase > 62) { throw new Exception\InvalidArgumentException( "Unsupported base: {$fromBase}, should be 2..62" ); } if ($toBase < 2 || $toBase > 62) { throw new Exception\InvalidArgumentException( "Unsupported base: {$toBase}, should be 2..62" ); } if ($fromBase <= 36 && $toBase <= 36) { return gmp_strval(gmp_init($operand, $fromBase), $toBase); } $sign = (strpos($operand, '-') === 0) ? '-' : ''; $operand = ltrim($operand, '-+'); $chars = self::BASE62_ALPHABET; // convert operand to decimal if ($fromBase !== 10) { $decimal = '0'; for ($i = 0, $len = strlen($operand); $i < $len; $i++) { $decimal = gmp_mul($decimal, $fromBase); $decimal = gmp_add($decimal, strpos($chars, $operand[$i])); } } else { $decimal = gmp_init($operand); } if ($toBase == 10) { return gmp_strval($decimal); } // convert decimal to base $result = ''; do { list($decimal, $remainder) = gmp_div_qr($decimal, $toBase); $pos = gmp_strval($remainder); $result = $chars[$pos] . $result; } while (gmp_cmp($decimal, '0')); return $sign . $result; } }