<?php
namespace Engine; class NumberConvertor { static public function baseEncode($number, $alphabet = 'alphabet:full') { if (is_float($number)) { $div = (int)floor($number/PHP_INT_MAX); $mod = (int)($number - ($div*PHP_INT_MAX)); $number = $mod; } $alphabet = self::expandAlphabet($alphabet); $alphabetL = strlen($alphabet); $ret = ""; if ($number==0) { return $alphabet[0]; } while ($number) { $ret.= $alphabet[$number % $alphabetL]; $number = floor($number / $alphabetL); } return strrev($ret); } static public function baseDecode($str, $alphabet = 'alphabet:full') { $alphabet = self::expandAlphabet($alphabet); $alphabetL = strlen($alphabet); $alphabetRev = array_flip(str_split($alphabet, 1)); $ret = 0; while (strlen($str[0])) { $ret = $ret * $alphabetL + $alphabetRev[$str[0]]; $str = substr($str, 1); } return $ret; } static protected function expandAlphabet($alphabet) { switch($alphabet) { case 'alphabet:hex': return '0123456789abcdef'; break; case 'alphabet:lowercaseLetters': return '0123456789abcdefghijklmnopqrstuvwxyz'; break; case 'alphabet:full': return '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; break; } return $alphabet; } } 