function comparebit($key, $value) { if (isset($this->_bitmap[$key1])) { if (gmp_and($this->_bitmap[$key1], $value)) { return true; } } return false; }
/** * {@inheritdoc} */ public function encodeSFixed64($sFixed64) { $value = $this->is32Bit ? gmp_and($sFixed64, '0x0ffffffffffffffff') : gmp_init(sprintf('%u', $sFixed64)); $bytes = ''; for ($i = 0; $i < 8; ++$i) { $bytes .= chr(gmp_intval(gmp_and($value, $this->gmp_xff))); $value = gmp_div_q($value, $this->gmp_x100); } return $bytes; }
/** * @dataProvider providerTestTAGLong */ public function testPutTAGLong($value) { $fPtr = fopen($this->vFile->url(), 'wb'); // 32-bit longs seem to be too long for pack() on 32-bit machines. Split into 4x16-bit instead. $quarters[0] = gmp_div(gmp_and($value, '0xFFFF000000000000'), gmp_pow(2, 48)); $quarters[1] = gmp_div(gmp_and($value, '0x0000FFFF00000000'), gmp_pow(2, 32)); $quarters[2] = gmp_div(gmp_and($value, '0x00000000FFFF0000'), gmp_pow(2, 16)); $quarters[3] = gmp_and($value, '0xFFFF'); $binary = pack('nnnn', gmp_intval($quarters[0]), gmp_intval($quarters[1]), gmp_intval($quarters[2]), gmp_intval($quarters[3])); $this->dataHandler->putTAGLong($fPtr, $value); $this->assertSame($binary, $this->vFile->getContent()); }
/** * Return netmask * * @return IPv6 */ public function getMask() { if ($this->mask === null) { if ($this->prefix == 0) { $this->mask = new $this->ip_class(0); } else { $max_int = gmp_init(constant("{$this->ip_class}::MAX_INT")); $mask = gmp_shiftl($max_int, constant("{$this->ip_class}::NB_BITS") - $this->prefix); $mask = gmp_and($mask, $max_int); // truncate to 128 bits only $this->mask = new $this->ip_class($mask); } } return $this->mask; }
/** * @param string $octets * * @throws InvalidArgumentException if the given octets represent a malformed base-128 value or the decoded value would exceed the the maximum integer length * * @return int */ public static function decode($octets) { $bitsPerOctet = 7; $value = gmp_init(0, 10); $i = 0; $leftShift = function ($number, $positions) { return gmp_mul($number, gmp_pow(2, $positions)); }; while (true) { if (!isset($octets[$i])) { throw new InvalidArgumentException(sprintf('Malformed base-128 encoded value (0x%s).', strtoupper(bin2hex($octets)) ?: '0')); } $octet = gmp_init(ord($octets[$i++]), 10); $l1 = $leftShift($value, $bitsPerOctet); $r1 = gmp_and($octet, 0x7f); $value = gmp_add($l1, $r1); if (0 === gmp_cmp(gmp_and($octet, 0x80), 0)) { break; } } return gmp_strval($value); }
/** * Calculate Wang hash for 64bit unsigned integer using GMP library * PHP only supports signed integers even with 64bit version * * See <code/nel/include/nel/misc/wang_hash.h> on https://bitbucket.org/ryzom/ryzomcore * * @param string $key * * @return string hash */ function wang_hash64($key) { // force $key to be base 10 $key = gmp_init($key, 10); //$key = (~$key) + ($key << 21); $key = gmp_add(gmp_com($key), gmp_mul($key, 1 << 21)); //$key = $key ^ ($key >> 24); $key = gmp_xor($key, gmp_div($key, 1 << 24)); //$key = $key * 265; $key = gmp_mul($key, 265); //$key = $key ^ ($key >> 14); $key = gmp_xor($key, gmp_div($key, 1 << 14)); //$key = $key * 21; $key = gmp_mul($key, 21); //$key = $key ^ ($key >> 28); $key = gmp_xor($key, gmp_div($key, 1 << 28)); //$key = $key + ($key << 31); $key = gmp_add($key, gmp_mul($key, gmp_pow(2, 31))); // limit to 64bit $key = gmp_and($key, "0xFFFFFFFFFFFFFFFF"); return gmp_strval($key, 10); }
/** * Bitwise AND * * @param $value mixed anything that can be converted into an IP object * @return IP */ public function bit_and($value) { if (!$value instanceof self) { $value = new $this->class($value); } return new $this->class(gmp_and($this->ip, $value->ip)); }
private function decrypt($encrypted_password) { $encrypted_password = trim($encrypted_password); if (!strlen($encrypted_password)) { return ''; } $decoded_password = hextostr($encrypted_password); $decrypted_password = ''; $seed = 0x2a9a; for ($i = 0; $i < strlen($decoded_password); $i++) { $decrypted_password .= chr(ord($decoded_password[$i]) ^ $seed >> 8 & 0xff); $seed += ord($decoded_password[$i]); $seed = hexdec(gmp_strval(gmp_and(gmp_add(gmp_mul("{$seed}", "0x8141"), "0x3171"), "0xffff"), 16)); } return $decrypted_password; }
/** * @param int[] $bytes array of ascii codes of bytes to decode * @return string represenation of decoded long. */ static function decode_long_from_array($bytes) { $b = array_shift($bytes); $g = gmp_init($b & 0x7f); $shift = 7; while (0 != ($b & 0x80)) { $b = array_shift($bytes); $g = gmp_or($g, self::shift_left($b & 0x7f, $shift)); $shift += 7; } $val = gmp_xor(self::shift_right($g, 1), gmp_neg(gmp_and($g, 1))); return gmp_strval($val); }
public static function mul($x2, Point $p1) { $e = $x2; if (self::cmp($p1, self::INFINITY) == 0) { return self::INFINITY; } if ($p1->order != null) { $e = gmp_mod($e, $p1->order); } if (gmp_cmp($e, 0) == 0) { return self::INFINITY; } if (gmp_cmp($e, 0) > 0) { $e3 = gmp_mul(3, $e); $negative_self = new Point($p1->curve, $p1->x, gmp_neg($p1->y), $p1->order); $i = gmp_div(self::leftmost_bit($e3), 2); $result = $p1; while (gmp_cmp($i, 1) > 0) { $result = self::double($result); if (gmp_cmp(gmp_and($e3, $i), 0) != 0 && gmp_cmp(gmp_and($e, $i), 0) == 0) { $result = self::add($result, $p1); } if (gmp_cmp(gmp_and($e3, $i), 0) == 0 && gmp_cmp(gmp_and($e, $i), 0) != 0) { $result = self::add($result, $negative_self); } $i = gmp_div($i, 2); } return $result; } }
public function sFixed64_gmp($value) { static $xff, $x100; if (NULL === $xff) { $xff = gmp_init(0xff); $x100 = gmp_init(0x100); } $value = PHP_INT_SIZE < 8 ? gmp_and($value, '0x0ffffffffffffffff') : gmp_init(sprintf('%u', $value)); $bytes = ''; for ($i = 0; $i < 8; $i++) { $bytes .= chr(gmp_intval(gmp_and($value, $xff))); $value = gmp_div_q($value, $x100); } $this->write($bytes); }
/** * Normalize * * Deletes leading zeros and truncates (if necessary) to maintain the appropriate precision * * @return Math_BigInteger * @access private */ function _normalize($result) { $result->precision = $this->precision; $result->bitmask = $this->bitmask; switch (MATH_BIGINTEGER_MODE) { case MATH_BIGINTEGER_MODE_GMP: if (!empty($result->bitmask->value)) { $result->value = gmp_and($result->value, $result->bitmask->value); } return $result; case MATH_BIGINTEGER_MODE_BCMATH: if (!empty($result->bitmask->value)) { $result->value = bcmod($result->value, $result->bitmask->value); } return $result; } if (!count($result->value)) { return $result; } for ($i = count($result->value) - 1; $i >= 0; $i--) { if ($result->value[$i]) { break; } unset($result->value[$i]); } if (!empty($result->bitmask->value)) { $length = min(count($result->value), count($this->bitmask->value)); $result->value = array_slice($result->value, 0, $length); for ($i = 0; $i < $length; $i++) { $result->value[$i] = $result->value[$i] & $this->bitmask->value[$i]; } } return $result; }
function myrand($max, &$seed) { $seed = hexdec(gmp_strval(gmp_and(gmp_add(gmp_mul("{$seed}", "0x8088405"), "1"), "0xffffffff"), 16)); $v = hexdec(gmp_strval(gmp_and(gmp_shiftr(gmp_mul("0x" . dechex($seed), "{$max}"), "32"), "0xffffffff"), 16)); return $v; }
public function sign($message) { $curve = \fpoirotte\Pssht\ED25519::getInstance(); $h = hash('sha512', $this->sk, true); $a = gmp_add(gmp_pow(2, 256 - 2), gmp_and(gmp_init(bin2hex(strrev($h)), 16), gmp_sub(gmp_pow(2, 254), 8))); $r = static::Hint(substr($h, 32) . $message); $R = $curve->scalarmult($curve->B, $r); $t = static::encodepoint($R) . $this->pk . $message; $S = gmp_mod(gmp_add($r, gmp_mul(static::Hint($t), $a)), $curve->l); return static::encodepoint($R) . static::encodeint($S); }
/** * @param int $BitOffset * @param int $ValueMask * @param int $Value * * @return void */ private function Set($BitOffset, $ValueMask, $Value) { $this->Data = gmp_or(gmp_and($this->Data, gmp_com(self::ShiftLeft($ValueMask, $BitOffset))), self::ShiftLeft(gmp_and($Value, $ValueMask), $BitOffset)); }
public static function ipv6NetworkFromAddr($addr, $prefix) { $size = 128 - $prefix; $addr = gmp_init('0x' . str_replace(':', '', $addr)); $mask = gmp_init('0x' . str_replace(':', '', Ip::ipv6PrefixToMask($prefix))); $prefix = gmp_and($addr, $mask); return gmp_strval($prefix, 16); }
/** * @param string $ip * @param int $mask */ public function cidrToLongRange($ip, $mask) { // complementary mask $cmask = 32 - $mask; // binary complementary mask transformed to long int $ones = gmp_strval(gmp_sub(gmp_strval(gmp_pow("2", $cmask)), "1")); // long int mask $mask = gmp_strval(gmp_mul(gmp_strval(gmp_pow("2", $cmask)), gmp_strval(gmp_sub(gmp_strval(gmp_pow("2", $mask)), "1")))); // string subnet $this->longLeftRange = gmp_strval(gmp_and(sprintf("%u", ip2long($ip)), $mask), 10); // string broadcast ip $this->longRightRange = gmp_strval(gmp_add($this->longLeftRange, $ones)); }
/** * ConvertToCommunityID * - Converts a 17-digit Community ID (e.g. 76561197960435530) into a SteamID (e.g. STEAM_0:1:3144145) * @return SteamID as a string */ function convertToCommunityID() { if (!empty($this->steamID64)) { $Y = $this->steamID64 % 2; //Parity bit at end of 64-bit ID $Z = gmp_and($this->steamID64, "0xFFFFFFFF"); //Get the Account ID $Z = gmp_strval(gmp_div($Z, 2)); return "STEAM_0:{$Y}:{$Z}"; } }
/** * Is number a power of 2 (e.g. an exponential value of 2)? * * @param string|resource $number Numeric string; or GMP resource. * * @return boolean TRUE if `$number` is a power of 2. * * @throws exception If invalid types are passed through arguments list. */ public function is_power_of_2($number) { $this->check_arg_types(array('numeric', 'resource'), func_get_args()); $number = $this->resource($number); // Resource. return !gmp_cmp(gmp_and($number, gmp_sub($number, $this->_1)), $this->_0); }
public static function BitwiseAND($Number1, $Number2) { return gmp_and($Number1, $Number2); }
/** * Scan the blobs table for rows not registered in blob_tracking (and thus not * registered in the text table). * * Orphan blobs are indicative of DB corruption. They are inaccessible and * should probably be deleted. */ function findOrphanBlobs() { if (!extension_loaded('gmp')) { echo "Can't find orphan blobs, need bitfield support provided by GMP.\n"; return; } $dbw = wfGetDB(DB_MASTER); foreach ($this->clusters as $cluster) { echo "Searching for orphan blobs in {$cluster}...\n"; $lb = wfGetLBFactory()->getExternalLB($cluster); try { $extDB = $lb->getConnection(DB_SLAVE); } catch (DBConnectionError $e) { if (strpos($e->error, 'Unknown database') !== false) { echo "No database on {$cluster}\n"; } else { echo "Error on {$cluster}: " . $e->getMessage() . "\n"; } continue; } $table = $extDB->getLBInfo('blobs table'); if (is_null($table)) { $table = 'blobs'; } if (!$extDB->tableExists($table)) { echo "No blobs table on cluster {$cluster}\n"; continue; } $startId = 0; $batchesDone = 0; $actualBlobs = gmp_init(0); $endId = $extDB->selectField($table, 'MAX(blob_id)', false, __METHOD__); // Build a bitmap of actual blob rows while (true) { $res = $extDB->select($table, array('blob_id'), array('blob_id > ' . $extDB->addQuotes($startId)), __METHOD__, array('LIMIT' => $this->batchSize, 'ORDER BY' => 'blob_id')); if (!$res->numRows()) { break; } foreach ($res as $row) { gmp_setbit($actualBlobs, $row->blob_id); } $startId = $row->blob_id; ++$batchesDone; if ($batchesDone >= $this->reportingInterval) { $batchesDone = 0; echo "{$startId} / {$endId}\n"; } } // Find actual blobs that weren't tracked by the previous passes // This is a set-theoretic difference A \ B, or in bitwise terms, A & ~B $orphans = gmp_and($actualBlobs, gmp_com($this->trackedBlobs[$cluster])); // Traverse the orphan list $insertBatch = array(); $id = 0; $numOrphans = 0; while (true) { $id = gmp_scan1($orphans, $id); if ($id == -1) { break; } $insertBatch[] = array('bo_cluster' => $cluster, 'bo_blob_id' => $id); if (count($insertBatch) > $this->batchSize) { $dbw->insert('blob_orphans', $insertBatch, __METHOD__); $insertBatch = array(); } ++$id; ++$numOrphans; } if ($insertBatch) { $dbw->insert('blob_orphans', $insertBatch, __METHOD__); } echo "Found {$numOrphans} orphan(s) in {$cluster}\n"; } }
/** * Bitwise "and" (&) * * @param mixed $number * @access public * @return self */ public function bitAnd($number) { $result = gmp_and($this->getRawValue(), static::upgradeParam($number)->getRawValue()); return static::factory($result); }
public static function mul($x2, Point $p1) { if (extension_loaded('gmp') && USE_EXT == 'GMP') { $e = $x2; if (self::cmp($p1, self::$infinity) == 0) { return self::$infinity; } if ($p1->order != null) { $e = gmp_strval(gmp_Utils::gmp_mod2($e, $p1->order)); } if (gmp_cmp($e, 0) == 0) { return self::$infinity; } $e = gmp_strval($e); if (gmp_cmp($e, 0) > 0) { $e3 = gmp_mul(3, $e); $negative_self = new Point($p1->curve, $p1->x, gmp_strval(gmp_sub(0, $p1->y)), $p1->order); $i = gmp_div(self::leftmost_bit($e3), 2); $result = $p1; while (gmp_cmp($i, 1) > 0) { $result = self::double($result); if (gmp_cmp(gmp_and($e3, $i), 0) != 0 && gmp_cmp(gmp_and($e, $i), 0) == 0) { $result = self::add($result, $p1); } if (gmp_cmp(gmp_and($e3, $i), 0) == 0 && gmp_cmp(gmp_and($e, $i), 0) != 0) { $result = self::add($result, $negative_self); } $i = gmp_strval(gmp_div($i, 2)); } return $result; } } else { throw new ErrorException("Please install GMP"); } }
<?php # show squares to display free/used subnet # fetch section $section = (array) $Tools->fetch_object("sections", "id", $subnet['sectionId']); print "<br><h4>" . _('Visual subnet display') . " <i class='icon-gray icon-info-sign' rel='tooltip' data-html='true' title='" . _('Click on IP address box<br>to manage IP address') . "!'></i></h4><hr>"; print "<div class='ip_vis'>"; # set limits - general $start_visual = gmp_strval(gmp_and("0xffffffff", (int) $Subnets->transform_to_decimal($subnet_detailed['network']))); $stop_visual = gmp_strval(gmp_and("0xffffffff", (int) $Subnets->transform_to_decimal($subnet_detailed['broadcast']))); # remove subnet and bcast if mask < 31 if ($subnet['mask'] > 30) { } elseif ($section['strictMode'] == 1) { $start_visual = gmp_strval(gmp_add($start_visual, 1)); $stop_visual = gmp_strval(gmp_sub($stop_visual, 1)); } # we need to reindex addresses to have ip address in decimal as key! $visual_addresses = array(); if ($addresses_visual) { foreach ($addresses_visual as $a) { $visual_addresses[$a->ip_addr] = (array) $a; } } # print for ($m = $start_visual; $m <= $stop_visual; $m = gmp_strval(gmp_add($m, 1))) { # already exists if (array_key_exists((string) $m, $visual_addresses)) { # fix for empty states - if state is disabled, set to active if (strlen($visual_addresses[$m]['state']) == 0) { $visual_addresses[$m]['state'] = 1; }
/** * Logical And * * @param Math_BigInteger $x * @access public * @internal Implemented per a request by Lluis Pamies i Juarez <lluis _a_ pamies.cat> * @return Math_BigInteger */ function bitwise_and($x) { switch (MATH_BIGINTEGER_MODE) { case MATH_BIGINTEGER_MODE_GMP: $temp = new Math_BigInteger(); $temp->value = gmp_and($this->value, $x->value); return $temp; case MATH_BIGINTEGER_MODE_BCMATH: return new Math_BigInteger($this->toBytes() & $x->toBytes(), 256); } $result = new Math_BigInteger(); $x_length = count($x->value); for ($i = 0; $i < $x_length; $i++) { $result->value[] = $this->value[$i] & $x->value[$i]; } return $result->_normalize(); }
<?php // gmp_abs $abs1 = gmp_abs("274982683358"); $abs2 = gmp_abs("-274982683358"); echo gmp_strval($abs1) . "\n"; echo gmp_strval($abs2) . "\n"; // gmp_add $sum = gmp_add("123456789012345", "76543210987655"); echo gmp_strval($sum) . "\n"; // gmp_and $and1 = gmp_and("0xfffffffff4", "0x4"); $and2 = gmp_and("0xfffffffff4", "0x8"); echo gmp_strval($and1) . "\n"; echo gmp_strval($and2) . "\n"; // gmp_clrbit $clrbit = gmp_init("0xff"); gmp_clrbit($clrbit, 0); echo gmp_strval($clrbit) . "\n"; // gmp_cmp $cmp1 = gmp_cmp("1234", "1000"); // greater than $cmp2 = gmp_cmp("1000", "1234"); // less than $cmp3 = gmp_cmp("1234", "1234"); // equal to echo "{$cmp1} {$cmp2} {$cmp3}" . "\n"; // gmp_com $com = gmp_com("1234"); echo gmp_strval($com) . "\n"; // gmp_div_q
/** * Normalize * * Removes leading zeros and truncates (if necessary) to maintain the appropriate precision * * @param Math_BigInteger * @return Math_BigInteger * @see self::_trim() * @access private */ function _normalize($result) { $result->precision = $this->precision; $result->bitmask = $this->bitmask; switch (MATH_BIGINTEGER_MODE) { case MATH_BIGINTEGER_MODE_GMP: if ($this->bitmask !== false) { $result->value = gmp_and($result->value, $result->bitmask->value); } return $result; case MATH_BIGINTEGER_MODE_BCMATH: if (!empty($result->bitmask->value)) { $result->value = bcmod($result->value, $result->bitmask->value); } return $result; } $value =& $result->value; if (!count($value)) { return $result; } $value = $this->_trim($value); if (!empty($result->bitmask->value)) { $length = min(count($value), count($this->bitmask->value)); $value = array_slice($value, 0, $length); for ($i = 0; $i < $length; ++$i) { $value[$i] = $value[$i] & $this->bitmask->value[$i]; } } return $result; }
/** * @param $value * @param $mask * * @return bool */ public static function hasAny($value, $mask) { return gmp_cmp(gmp_and($value, $mask), 0) !== 0; }
/** * Convert an IPv6 address and prefix size to an address range for the network. * * This will take an IPv6 address and prefix and return the first and last address available for the network. * * @param string $addr A valid IPv6 address * @param integer $prefix The prefix size, an integer between 1 and 127 (inclusive) * @return array An array with two strings containing the start and end address for the IPv6 network */ function inet6_to_range($addr, $prefix) { $size = 128 - $prefix; $addr = gmp_init('0x' . str_replace(':', '', inet6_expand($addr))); $mask = gmp_init('0x' . str_replace(':', '', inet6_expand(inet6_prefix_to_mask($prefix)))); $prefix = gmp_and($addr, $mask); $start = gmp_strval(gmp_add($prefix, '0x1'), 16); $end = '0b'; for ($i = 0; $i < $size; $i++) { $end .= '1'; } $end = gmp_strval(gmp_add($prefix, gmp_init($end)), 16); for ($i = 0; $i < 8; $i++) { $start_result .= substr($start, $i * 4, 4); if ($i != 7) { $start_result .= ':'; } } // for for ($i = 0; $i < 8; $i++) { $end_result .= substr($end, $i * 4, 4); if ($i != 7) { $end_result .= ':'; } } // for $result = array(inet6_compress($start_result), inet6_compress($end_result)); return $result; }
<?php var_dump(gmp_strval(gmp_and("111111", "2222222"))); var_dump(gmp_strval(gmp_and(123123, 435234))); var_dump(gmp_strval(gmp_and(555, "2342341123"))); var_dump(gmp_strval(gmp_and(-1, 3333))); var_dump(gmp_strval(gmp_and(4545, -20))); var_dump(gmp_strval(gmp_and("test", "no test"))); $n = gmp_init("987657876543456"); var_dump(gmp_strval(gmp_and($n, "34332"))); $n1 = gmp_init("987657878765436543456"); var_dump(gmp_strval(gmp_and($n, $n1))); var_dump(gmp_and($n, $n1, 1)); var_dump(gmp_and(1)); var_dump(gmp_and(array(), 1)); var_dump(gmp_and(1, array())); var_dump(gmp_and(array(), array())); echo "Done\n";