有人可以告诉我如何编写一个php函数,将基数为36的字符串转换为基数为10的整数而不使用基本转换函数
该功能应该像这样工作
echo base36_to_base10('614qa'); //prints 10130482
echo base36_to_base10('614z1'); //prints 10130797
答案 0 :(得分:3)
只需使用原生base_convert
功能:
echo base_convert('614qa', 36, 10);
或者如果您愿意:
function base36to10($value) {
return base_convert($value, 36, 10);
}
如果您不能或不会使用base_convert
,则应该这样做:
function base36to10($value) {
// check for correct input
if (preg_match('/^[0-9A-Z]+$/i', $value) == 0) {
return NULL;
}
// reverse and change to uppercase
$value = strtoupper(strrev($value));
// converted value
$converted = 0;
// cycle on character
for ($c = 0, $l = strlen($value); $c < $l; ++$c) {
// if the character is a digit
if (ctype_digit($value[$c])) {
// convert directly
$v = (int) $value[$c];
}
// else convert ascii value
else {
$v = ord($value[$c]) - 55; // -55 == 10 - 65
}
// add to converted
$converted += $v * pow(36, $c);
}
// now return
return $converted;
}
答案 1 :(得分:1)
使用符号数组的选项略有不同:
a
如何使用您的一个示例:
function base36_to_base10($input) {
$symbols = array('0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'
,'g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
//flip the array so symbols are keys (or just write it that way to begin with)
$symbols = array_flip($symbols);
// reverse input string and convert to array
// (reversing the string simplifies incrementing place value as you iterate it)
$x = str_split(strrev($input));
$sum = 0;
foreach ($x as $place => $symbol) {
// increment sum with base 10 representation of base 36 place value
$sum += $symbols[$symbol] * pow(36, $place);
// or with PHP 5.6+
//$sum += $symbols[$symbol] * 36 ** $place;
}
return $sum;
}