/** * 返回客户端的IP地址 * @param boolean $is_int 所否返回整形IP地址 * @return int/string $ip 用户IP地址 */ public static function getIp($is_int = false) { //$ip = false; if (!empty($_SERVER['REMOTE_ADDR'])) { $ip = $_SERVER["REMOTE_ADDR"]; } else { if (!empty($_SERVER["HTTP_CLIENT_IP"])) { $ip = $_SERVER["HTTP_CLIENT_IP"]; } } if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ips = explode(", ", $_SERVER['HTTP_X_FORWARDED_FOR']); if ($ip) { array_unshift($ips, $ip); $ip = FALSE; } for ($i = 0; $i < count($ips); $i++) { if (!preg_match("/^(0|10|127|172\\.16|192\\.168)\\./", $ips[$i])) { $ip = $ips[$i]; break; } } } $ip = $ip ? $ip : $_SERVER['REMOTE_ADDR']; $ip = $ip ? $ip : '0.0.0.0'; return $is_int ? bindec(decbin(ip2long($ip))) : $ip; }
function mv_decrypt($str_hex, $key1, $key2) { $str_bin = ""; // 1. Convert hexadecimal string to binary string for ($i = 0; $i < 128; $i++) { $str_bin .= floor(hexdec($str_hex[floor($i / 4)]) / pow(2, 3 - $i % 4)) % 2; } // 2. Generate switch and XOR keys $key = array(); for ($i = 0; $i < 384; $i++) { $key1 = ($key1 * 11 + 77213) % 81371; $key2 = ($key2 * 17 + 92717) % 192811; $key[$i] = ($key1 + $key2) % 128; } // 3. Switch bits positions for ($i = 256; $i >= 0; $i--) { $temp = $str_bin[$key[$i]]; $str_bin[$key[$i]] = $str_bin[$i % 128]; $str_bin[$i % 128] = $temp; } // 4. XOR entire binary string for ($i = 0; $i < 128; $i++) { $str_bin[$i] = $str_bin[$i] ^ $key[$i + 256] & 1; } // 5. Convert binary string back to hexadecimal $str_hex = ""; for ($i = 0; $i < 32; $i++) { $str_hex .= dechex(bindec(substr($str_bin, $i * 4, 4))); } // 6. Return counted string return $str_hex; }
/** * Parses a DNUMBER token like PHP would. * * @param string $str A string number * * @return float The parsed number */ public static function parse($str) { // if string contains any of .eE just cast it to float if (false !== strpbrk($str, '.eE')) { return (double) $str; } // otherwise it's an integer notation that overflowed into a float // if it starts with 0 it's one of the special integer notations if ('0' === $str[0]) { // hex if ('x' === $str[1] || 'X' === $str[1]) { return hexdec($str); } // bin if ('b' === $str[1] || 'B' === $str[1]) { return bindec($str); } // oct // substr($str, 0, strcspn($str, '89')) cuts the string at the first invalid digit (8 or 9) // so that only the digits before that are used return octdec(substr($str, 0, strcspn($str, '89'))); } // dec return (double) $str; }
/** * 获取整形ip */ static function getInt($ip) { if (self::checkIP($ip)) { return bindec(decbin(ip2long($ip))); } return 0; }
function jugglingzero($data) { // inialise the variables $strBinary = ""; $arZeros = array(); $arSeries = array(); //explode the zeros; $arZeros = explode(" ", $data); //separate the zero flags to the series for ($i = 0; $i < count($arZeros); $i++) { if ($i % 2 == 0) { $arFlags[] = $arZeros[$i]; } else { $arSeries[] = $arZeros[$i]; } } // lets iterate through each flags for ($i = 0; $i < count($arFlags); $i++) { // if flag is equal to string zero if ($arFlags[$i] === "0") { // concatenate the series $strBinary .= $arSeries[$i]; } else { // replace the zero to one in the series // before concatenation $strBinary .= str_replace("0", "1", $arSeries[$i]); } } // then convert the binary to integer echo bindec($strBinary); }
/** * This method sets the value for the specified field. * * @access public * @param string $field the name of the field * @param mixed $value the value of the field * @throws Throwable\InvalidProperty\Exception indicates that the specified property is * either inaccessible or undefined */ public function __set($field, $value) { if (!array_key_exists($field, $this->values)) { throw new Throwable\InvalidProperty\Exception('Unable to set the specified property. Property :field is either inaccessible or undefined.', array(':field' => $field, ':value' => $value)); } $this->values[$field] = bindec(static::unpack($value, $this->boundary)); }
/** * Convert 32-bit SteamID to 64-bit SteamID * * @param string|int $userId * * @return string * @throws Exception */ public static function to64Bit($userId) { if (!function_exists('gmp_add')) { throw new Exception("GMP Library not installed. Cannot convert SteamIDs."); } return gmp_strval(gmp_add(gmp_mul(sprintf("%u", bindec(self::STEAM_ID_UPPER_BITS)), "4294967296"), sprintf("%u", $userId))); }
public static function timeFromParticle($particle) { /* * Return time */ return bindec(substr(decbin($particle), 0, 41)) - pow(2, 40) + 1 + self::EPOCH; }
/** * Checks a IPv4 address against a whitelist * * @param $ip IPv4 address in GeoIP or human readable format * @param $matches array of IPv4 addresses * @return true if $ip address is found in the $matches list */ function match_ip($ip, $matches) { if (!is_numeric($ip)) { $ip = IPv4_to_GeoIP($ip); } foreach ($matches as $chk) { $a = explode('/', $chk); //check against "80.0.0.0/8" format if (count($a) == 2) { $lo = IPv4_to_GeoIP($a[0]); if ($ip >= $lo) { $hi = $lo + bindec('1' . str_repeat('0', 32 - $a[1])) - 1; //echo "lo: ".GeoIP_to_IPv4($lo)." (".$lo.")\n"; //echo "hi: ".GeoIP_to_IPv4($hi)." (".$hi.")\n"; if ($ip <= $hi) { return true; } } } else { if ($ip == IPv4_to_GeoIP($chk)) { return true; } } } return false; }
public function run(&$arrData, $arrConf) { if (empty($arrData) || !is_array($arrData)) { return false; } $arrBitZoneConf = Util::getConf('/bitzone', 'BITZONE'); $arrBitZoneConf = $this->analysisConf($arrBitZoneConf); if (empty($arrBitZoneConf)) { return false; } // 遍历获得asResult->item->0/1/..->urls->asurls->strategys中的标志位数组 // 取得配置中各标志位在上述数组位置中的值 // 将最终解析出来的标志位值加入asResult->item->0/1/..->dispData->strategybits中 if (!empty($arrData['uiData']['asResult']['item']) && is_array($arrData['uiData']['asResult']['item'])) { foreach ($arrData['uiData']['asResult']['item'] as &$asResultItem) { $arrBitZoneInfo = array(); if (!empty($asResultItem['urls']['asUrls']['strategys']) && is_array($asResultItem['urls']['asUrls']['strategys'])) { foreach ($arrBitZoneConf as $strTipKey => $arrTipConfInfo) { $strTipValue = ''; foreach ($arrTipConfInfo as $intSection => $arrPos) { $intStrategySectionNum = intval($asResultItem['urls']['asUrls']['strategys'][$intSection]); foreach ($arrPos as $intPos) { $intTmp = ($intStrategySectionNum & pow(2, $intPos)) == 0 ? 0 : 1; $strTipValue = $strTipValue === '' ? $intTmp : $strTipValue . $intTmp; } } $arrBitZoneInfo[$strTipKey] = bindec($strTipValue); } } $asResultItem['dispData']['strategybits'] = $arrBitZoneInfo; } } return true; }
function make_cache($type, $from, $to, $cache_time, $rewrite = false) { $hour_key = date('H', $from); // Кэш дневной ленты переходов $params = array('type' => 'basic', 'part' => 'hour', 'filter' => array(), 'group_by' => $type, 'subgroup_by' => $type, 'conv' => 'all', 'mode' => '', 'col' => 'sale_lead', 'from' => date('Y-m-d H:i:s', $from), 'to' => date('Y-m-d H:i:s', $to), 'cache' => 2); $arr_report_data = get_clicks_report_grouped2($params); /* dmp($params); dmp($arr_report_data); die();*/ $str = join('', $arr_report_data['click_params']) . join('', $arr_report_data['campaign_params']); echo $str . '<br />'; if (empty($arr_report_data['data'])) { return false; } foreach ($arr_report_data['data'] as $k => $v) { $r = $v[$hour_key]; $ins = array('type' => $type, 'id' => $r['id'], 'time' => $cache_time, 'name' => $r['name'], 'price' => $r['price'], 'unique' => $r['unique'], 'income' => $r['income'], 'direct' => $r['direct'], 'sale' => $r['sale'], 'lead' => $r['lead'], 'act' => $r['act'], 'out' => $r['out'], 'cnt' => $r['cnt'], 'sale_lead' => $r['sale_lead'], 'rebuild' => 0, 'params' => bindec($str)); $q = insertsql($ins, 'tbl_clicks_cache_hour', true); echo $q . '<br />'; db_query($q); } if ($rewrite) { $q = "update `tbl_clicks_cache_hour` set `rebuild` = '0' where `time` = '" . $cache_time . "'"; db_query($q); } return true; }
public function createCode() { for ($i = 0; $i < 4; $i++) { $this->text .= rand(0, 1); } $this->checkcode = bindec(intval($this->text)); }
/** * Decodes base32 * * @param string $base32String Base32 encoded string * @return string Clear text string */ function base32decode($base32String) { $base32alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567='; // Only work in upper cases $base32String = strtoupper($base32String); // Remove anything that is not base32 alphabet $pattern = '/[^A-Z2-7]/'; $base32String = preg_replace($pattern, '', $base32String); if (strlen($base32String) == 0) { // Gives an empty string return ''; } $base32Array = str_split($base32String); $string = ''; foreach ($base32Array as $str) { $char = strpos($base32alphabet, $str); // Ignore the padding character if ($char !== 32) { $string .= sprintf('%05b', $char); } } while (strlen($string) % 8 !== 0) { $string = substr($string, 0, strlen($string) - 1); } $binaryArray = base32chunk($string, 8); $realString = ''; foreach ($binaryArray as $bin) { // Pad each value to 8 bits $bin = str_pad($bin, 8, 0, STR_PAD_RIGHT); // Convert binary strings to ASCII $realString .= chr(bindec($bin)); } return $realString; }
public static function getUniqueID2() { // The field names refer to RFC 4122 section 4.1.2 $uuid = sprintf('%04x%04x-%04x-%03x4-%04x-%04x%04x%04x', mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 4095), bindec(substr_replace(sprintf('%016b', mt_rand(0, 65535)), '01', 6, 2)), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535)); $uuid = 'id' . str_replace('-', '', $uuid); return $uuid; }
function update_field($field) { if (!$this->id) { return ERR_NO_ORDER_CHOSEN; } if (!isset($this->allow_single_update)) { return ERR_NOT_ALLOWED_TO_CHANGE_FIELD; } if (!in_array($field, $this->allow_single_update)) { return ERR_NOT_ALLOWED_TO_CHANGE_FIELD; } $this->fetch_data(); $input_data = $this->data; $new_value = $this->data[$field] ? 0 : 1; if ($field == 'level') { $this->get_level(); $lev = $this->level; $idx = $_REQUEST['data']['subfield']; $lev[$idx] = $lev[$idx] ? 0 : 1; krsort($lev); foreach ($lev as $val) { $levinv .= $val; } $levinv = bindec($levinv); $new_value = $levinv; } if ($err = $this->set($field, $new_value)) { return $err; } return 0; }
/** * getRank * * @access public * @param numeric $rgb2 rgb1 * @param numeric $rgb2 rgb2 * @param numeric $rgb3 rgb3 * @return int */ public function getRank($rgb1, $rgb2, $rgb3) { $a = $this->dec2bin($rgb1); $b = $this->dec2bin($rgb2); $c = $this->dec2bin($rgb3); return bindec($a[0] . $a[5] . $b[0] . $b[5] . $c[0] . $c[5]); }
function ipMask($ip, $mask) { $arrip = explode('.', $ip); $arrmask = explode('.', $mask); $maskip = bindec(decbin($arrip[0]) & decbin($arrmask[0])) . '.' . bindec(decbin($arrip[1]) & decbin($arrmask[1])) . '.' . bindec(decbin($arrip[2]) & decbin($arrmask[2])) . '.' . bindec(decbin($arrip[3]) & decbin($arrmask[3])); return $maskip; }
public static function setFolderPermissions($dir, $io) { $changePerms = function ($path, $perms, $io) { $currentPerms = octdec(substr(sprintf('%o', fileperms($path)), -4)); if (($currentPerms & $perms) == $perms) { return; } $res = chmod($path, $currentPerms | $perms); if ($res) { $io->write('Permissions set on ' . $path); } else { $io->write('Failed to set permissions on ' . $path); } }; $walker = function ($dir, $perms, $io) use(&$walker, $changePerms) { $files = array_diff(scandir($dir), ['.', '..']); foreach ($files as $file) { $path = $dir . '/' . $file; if (!is_dir($path)) { continue; } $changePerms($path, $perms, $io); $walker($path, $perms, $io); } }; $worldWritable = bindec('0000000111'); $walker($dir . '/Tmp', $worldWritable, $io); $changePerms($dir . '/Tmp', $worldWritable, $io); $changePerms($dir . '/Tmp/Log', $worldWritable, $io); }
/** * Try get the range instance starting from its string representation. * * @param string|mixed $range * * @return static|null */ public static function fromString($range) { $result = null; if (is_string($range)) { $parts = explode('/', $range); if (count($parts) === 2) { $address = Factory::addressFromString($parts[0]); if ($address !== null) { if (preg_match('/^[0-9]{1,9}$/', $parts[1])) { $networkPrefix = @intval($parts[1]); if ($networkPrefix >= 0) { $addressBytes = $address->getBytes(); $totalBytes = count($addressBytes); $numDifferentBits = $totalBytes * 8 - $networkPrefix; if ($numDifferentBits >= 0) { $numSameBytes = $networkPrefix >> 3; $sameBytes = array_slice($addressBytes, 0, $numSameBytes); $differentBytesStart = $totalBytes === $numSameBytes ? array() : array_fill(0, $totalBytes - $numSameBytes, 0); $differentBytesEnd = $totalBytes === $numSameBytes ? array() : array_fill(0, $totalBytes - $numSameBytes, 255); $startSameBits = $networkPrefix % 8; if ($startSameBits !== 0) { $varyingByte = $addressBytes[$numSameBytes]; $differentBytesStart[0] = $varyingByte & bindec(str_pad(str_repeat('1', $startSameBits), 8, '0', STR_PAD_RIGHT)); $differentBytesEnd[0] = $differentBytesStart[0] + bindec(str_repeat('1', 8 - $startSameBits)); } $result = new static(Factory::addressFromBytes(array_merge($sameBytes, $differentBytesStart)), Factory::addressFromBytes(array_merge($sameBytes, $differentBytesEnd)), $networkPrefix); } } } } } } return $result; }
static function calcRange($iparray) { //print_r($iparray); $iparray = array_unique($iparray); $iparray = array_map("ip2long", $iparray[0]); sort($iparray); $iparray = array_map("long2ip", $iparray); $ip_begin = $iparray[0]; $ip_end = $iparray[count($iparray) - 1]; $ip_begin_bin = self::ip2bin($ip_begin); $ip_end_bin = self::ip2bin($ip_end); $ip_shortened = self::findMatch(implode('', $ip_begin_bin), implode('', $ip_end_bin)); $cidr_range = strlen($ip_shortened); $cidr_difference = 32 - $cidr_range; $cidr_begin = $ip_shortened . str_repeat('0', $cidr_difference); $cidr_end = $ip_shortened . str_repeat('1', $cidr_difference); $ip_count = bindec($cidr_end) - bindec($cidr_begin) + 1; $ips = array(); foreach ($iparray as $ip) { $ips[] = array('ip' => $ip, 'bin' => implode('.', self::ip2bin($ip)), 'rdns' => gethostbyaddr($ip), 'long' => ip2long($ip), 'hex' => implode('.', self::ip2hex($ip)), 'octal' => implode('.', self::ip2oct($ip)), 'radians' => implode('/', self::ip2rad($ip)), 'base64' => implode('.', self::ip264($ip)), 'alpha' => implode('.', self::ip2alpha($ip))); } usort($ips, array('IPCalc', 'ipsort')); $tmp = self::calcCIDR($ip_begin . '/' . $cidr_range); return array('begin' => $tmp['begin'], 'end' => $tmp['end'], 'count' => $tmp['count'], 'suffix' => $cidr_range, 'ips' => $ips); }
public function strdecodebase32($str) { if (strlen($str) % 8 > 0) { throw new Exception("Str length must be a multiple of 8"); } if (empty($str)) { return ""; } $len = strpos($str, "="); if ($len !== FALSE) { $str = substr($str, 0, $len); } $quanta = str_split($str, 8); $decoded = ""; foreach ($quanta as $quantum) { $_8bitchars = ""; for ($i = 0; $i < strlen($quantum); $i++) { $code = strpos($this->charset, $quantum[$i]); if ($code === FALSE) { throw new Exception("Invalid charset."); } $_8bitchars .= str_pad(decbin($code), 5, "0", STR_PAD_LEFT); } foreach (str_split($_8bitchars, 8) as $char) { $decoded .= chr(bindec($char)); } } return $decoded; }
public function encode($data) { if (!is_string($data)) { $data = serialize($data); } if (empty($data)) { return ''; } if ($this->dictionnary === null) { $this->generateDictionnary($data); } $binaryString = ''; for ($i = 0; isset($data[$i]); ++$i) { $binaryString .= $this->dictionnary->get($data[$i]); } $splittedBinaryString = str_split('1' . $binaryString . '1', 8); $binaryString = ''; foreach ($splittedBinaryString as $i => $c) { while (strlen($c) < 8) { $c .= '0'; } $binaryString .= chr(bindec($c)); } return $binaryString; }
/** * Encodes data before writing to the client socket stream * @param string $payload * @param string $type * @param boolean $masked * @return type */ private function encode($payload, $type = self::EVENT_TYPE_TEXT, $masked = false) { $frameHead = []; $payloadLength = strlen($payload); switch ($type) { case self::EVENT_TYPE_TEXT: // first byte indicates FIN, Text-Frame (10000001): $frameHead[0] = self::ENCODE_TEXT; break; case self::EVENT_TYPE_CLOSE: // first byte indicates FIN, Close Frame(10001000): $frameHead[0] = self::ENCODE_CLOSE; break; case self::EVENT_TYPE_PING: // first byte indicates FIN, Ping frame (10001001): $frameHead[0] = self::ENCODE_PING; break; case self::EVENT_TYPE_PONG: // first byte indicates FIN, Pong frame (10001010): $frameHead[0] = self::ENCODE_PONG; break; } // set mask and payload length (using 1, 3 or 9 bytes) if ($payloadLength > self::PAYLOAD_MAX_BITS) { $payloadLengthBin = str_split(sprintf('%064b', $payloadLength), self::PAYLOAD_CHUNK); $frameHead[1] = $masked === true ? self::MASK_255 : self::MASK_127; for ($i = 0; $i < 8; $i++) { $frameHead[$i + 2] = bindec($payloadLengthBin[$i]); } // most significant bit MUST be 0 if ($frameHead[2] > self::MASK_127) { return ['type' => $type, 'payload' => $payload, 'error' => self::ERR_FRAME_TOO_LARGE]; } } elseif ($payloadLength > self::MASK_125) { $payloadLengthBin = str_split(sprintf('%016b', $payloadLength), self::PAYLOAD_CHUNK); $frameHead[1] = $masked === true ? self::MASK_254 : self::MASK_126; $frameHead[2] = bindec($payloadLengthBin[0]); $frameHead[3] = bindec($payloadLengthBin[1]); } else { $frameHead[1] = $masked === true ? $payloadLength + self::MASK_128 : $payloadLength; } // convert frame-head to string: foreach (array_keys($frameHead) as $i) { $frameHead[$i] = chr($frameHead[$i]); } if ($masked === true) { // generate a random mask: $mask = []; for ($i = 0; $i < 4; $i++) { $mask[$i] = chr(rand(0, self::MASK_255)); } $frameHead = array_merge($frameHead, $mask); } $frame = implode('', $frameHead); // append payload to frame: for ($i = 0; $i < $payloadLength; $i++) { $frame .= $masked === true ? $payload[$i] ^ $mask[$i % 4] : $payload[$i]; } return $frame; }
function calcSmallest($packets, $weight) { $checkStr = implode(array_fill(0, count($packets), 1)); $checkDec = bindec($checkStr); for ($i = 0; $i <= $checkDec; $i++) { $binStr = decbin($i); if (isset($smallest) && substr_count($binStr, "1") > $smallest[0]) { continue; } $binStrArr = str_split(str_pad($binStr, count($packets), "0", STR_PAD_LEFT)); $new_vals = []; foreach ($binStrArr as $key => $value) { $new_vals[] = $value * $packets[$key]; } $new_vals = array_filter($new_vals); if (array_sum($new_vals) == $weight) { $newLen = count($new_vals); $newQuan = array_product($new_vals); if (isset($smallest)) { if ($newLen <= $smallest[0] && $newQuan < $smallest[1]) { $smallest = [$newLen, $newQuan]; } } else { $smallest = [$newLen, $newQuan]; } } } return $smallest[1]; }
/** * @param Replay $replay * @param BinaryReader $br * @param Actor $actor * @return ActorProperty */ public static function deserialize($replay, $br, $actor) { $id = bindec(strrev($br->readBits($actor->getPropertyBits()))); $class = $actor->properties[$id]; $property = new self($id, $class); return new self(); }
function fund_detail() { if ($this->uri->segment(2)) { $this->uri->segment(2); $fund_id = bindec($this->uri->segment(2)); $select_filed = '*'; $tbl_name = 'tbl_fund as f'; $where_condition = array('f.fund_id' => $fund_id); $order_by_field = 'f.fund_id'; $order_by_type = 'desc'; $group_by_field = 'f.fund_id'; $join_tbl1 = ""; $join_condition1 = ""; $join_tbl2 = ""; $join_condition2 = ""; $data['art_data'] = $this->user_model->select_query_with_pagination($select_filed, $tbl_name, $where_condition, '', '', 'Y', $order_by_field, $order_by_type, $group_by_field, $join_tbl1, '', $join_condition1, $join_tbl2, $join_condition2, ''); $data['total_applicant'] = $this->user_model->check_no_rec('tbl_fund_applicant', array('app_fund_id' => $fund_id)); $data['open_found'] = $this->user_model->select_query_with_pagination($select_filed, $tbl_name, array('f.fund_status' => '1'), '', '', 'Y', $order_by_field, $order_by_type, $group_by_field, $join_tbl1, '', $join_condition1, $join_tbl2, $join_condition2, ''); if (!empty($data['art_data'])) { $this->load->view('header'); $this->load->view('funding_detail', $data); $this->load->view('footer'); } else { $redirect = base_url() . 'funding-list'; redirect($redirect); } } else { $redirect = base_url() . 'funding-list'; redirect($redirect); } }
/** * Consume an integer from an arbitrary number of bits in the stream * * @param int $cnt Length in bits of the integer */ function getInt($cnt) { $this->fetch($cnt); $ret = bindec(substr($this->bits, $this->pos - ($this->ofs << 3), $cnt)); $this->pos += $cnt; return $ret; }
function cidr_conv($net) { $start = strtok($net, '/'); $n = 3 - substr_count($net, '.'); if ($n > 0) { for ($i = $n; $i > 0; $i--) { $start .= '.0'; } } $bits1 = str_pad(decbin(ip2long($start)), 32, '0', 'STR_PAD_LEFT'); $net = pow(2, 32 - substr(strstr($net, '/'), 1)) - 1; $bits2 = str_pad(decbin($net), 32, '0', 'STR_PAD_LEFT'); $final = ''; for ($i = 0; $i < 32; $i++) { if ($bits1[$i] == $bits2[$i]) { $final .= $bits1[$i]; } if ($bits1[$i] == 1 && $bits2[$i] == 0) { $final .= $bits1[$i]; } if ($bits1[$i] == 0 && $bits2[$i] == 1) { $final .= $bits2[$i]; } } return $start . " - " . long2ip(bindec($final)); }
function bytes2double($number, $MNO, $STEP) { // echo 'Number has '.strlen($number).' bytes = '.$number.'<br/>'; //переворачиваем строку $number = strrev($number); //создаем массив $mas = NULL; for ($i = 0; $i < 8; $i++) { $mas[$i] = sprintf("%08b", ord($number[$i])); } // var_dump($mas); //создаем 64 битную строку $s = implode('', $mas); // echo 'S = '.$s.'<br/>'; //разделяем на биты знака, экспоненты и мантиссы $znak = substr($s, 0, 1); // echo 'ZNAK = '.$znak.'<br/>'; $exp = substr($s, 1, 11); // echo 'EXP = '.bindec($exp).'<br/>'; $mant = substr($s, 12, 52); // echo 'MANT = '.bindec($mant).'<br/>'; //находим множители $a = pow(-1, bindec($znak)); // echo 'A = '.$a.'<br/>'; $b = pow(2, bindec($exp) - $STEP - 1023); // echo 'B = '.$b.'<br/>'; $c = 1 + bindec($mant) / pow(2, 52); // echo 'C = '.$c.'<br/>'; //считаем результат // echo 'RESULT = '.($a*$b*$c*$MNO).'<br/>'; return $a * $b * $c * $MNO; }
/** * @param Replay $replay * @param BinaryReader $br * @param int $frameNumber * @return Replication */ public static function deserialize($replay, $br, $frameNumber) { $r = new self(); $r->actorId = bindec(strrev($br->readBits(10))); $r->channelState = $br->readBit(); if (!$r->channelState) { $replay->closeActor($r->actorId, $frameNumber); return $r; } $r->actorState = $br->readBit(); if ($r->actorState) { // New actor $r->propertyFlag = $br->readBit(); // seems to always be 0 since we are creating a new actor $r->actorObjectId = bindec(strrev($br->readBits(8))); $actor = $replay->createActor($r->actorId, $r->actorObjectId, $frameNumber); $actor->deserializeInit($br); print "Actor #{$actor->id} {$actor->class} R:{$actor->rotator} P:{$actor->position} O:{$actor->orientation}\n"; } else { // Existing actor print "existing actor\n"; $actor = $replay->getActor($r->actorId); while ($br->readBit()) { $actor->updateProperty(ActorProperty::deserialize($replay, $br, $actor)); } } return $r; }