1

我需要从 userId、subjectId 生成编码的唯一 id 并对其进行解码。编码数字不应重复,长度必须 <=12,并且只能是非负整数。userId 和 subjectId 来自数据库,其值、长度各不相同。

我使用了 base_convert 函数并将十进制数转换为八进制数。

/* Encode function - Converting from decimal to octal 
   $decNum = $usreId.'-'.$subjectId;
*/

function convertDecimalToOctal($decNum){
    $decToOctalNum ='';
    $hyphenPos ='';
    $decToOctal ='';

    $hyphenPos = !($tmp = strpos($decNum, '-')) ? 0 : $tmp; // Get Hyphen Position from string
    $decNum = str_replace('-', '', $decNum); //Replace '-' with '' and get number without '-'

    $decToOctal  = base_convert($decNum,10,8); // Convert from Decimal to Octal

    $decToOctalNum = ($hyphenPos . $decToOctal); // Append the hyphen position to converted octal number

    return $decToOctalNum;
}

/* Decode Function - Converting from octal to decimal */
function convertOctalToDecimal($octNum){
    $getHyphenPos ='';
    $octalToDec ='';
    $octalToDecNum ='';

    $getHyphenPos = substr($octNum, 0, 1); // get hyphen position(digit) from the octal number
    $octNum = substr($octNum, 1); // trim hyphen position off the octal number

    $octalToDec = base_convert($octNum,8,10); // Convert from Octal to Decimal
    $octalToDecNum = substr($octalToDec, 0, $getHyphenPos) . '-' . substr($octalToDec, $getHyphenPos); // Put the hyphen in the converted decimal number

    return $octalToDecNum;
}

根据 php.net,base_convert() 可能会由于与使用的内部“double”或“float”类型相关的属性而在大数字上失去精度。

我们如何确保这将为 userId 和 subjectId 的任意组合生成唯一编号?我们如何处理转换为浮点类型的大数?

我们不想在数据库中检查重复值。签入数据库需要很长时间。

谢谢。

4

0 回答 0