将整数转换为随机字符串然后再返回

Jea*_*lis 6 php

我想要的是将整数转换为字符串.例如,123456789可能会成为8GFsah93r ...你知道像Youtube,Pastebin等等.然后我想把它转换回来.

我正在使用大整数,例如:131569877435989900

看看这个链接:http://codepad.viper-7.com/wHKOMi

这是我尝试使用我在网络上找到的功能,显然......它没有正确转换回整数.我需要能够做到这一点的事情.

谢谢

Pet*_*rfy 4

好的,想法之一是使用字符数组作为数字系统的表示。然后您可以从基数 10 转换为基数 x,反之亦然。该值将更短且可读性较差(尽管如此,如果必须安全,您应该使用双向加密器对其进行加密)。

一个办法:

final class UrlShortener {

    private static $charfeed = Array(
    'a','A','b','B','c','C','d','D','e','E','f','F','g','G','h','H','i','I','j','J','k','K','l','L','m',
    'M','n','N','o','O','p','P','q','Q','r','R','s','S','t','T','u','U','v','V','w','W','x','X','y','Y',
    'z','Z','0','1','2','3','4','5','6','7','8','9');

    public static function intToShort($number) {
        $need = count(self::$charfeed);
        $s = '';

        do {
            $s .= self::$charfeed[$number%$need];
            $number = floor($number/$need);
        } while($number > 0);

        return $s;
    }

    public static function shortToInt($string) {
        $num = 0;
        $need = count(self::$charfeed);
        $length = strlen($string);

        for($x = 0; $x < $length; $x++) {
            $key = array_search($string[$x], self::$charfeed);
            $value = $key * pow($need, $x);
            $num += $value;
        }

        return $num;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以使用:

UrlShortener::intToShort(2);
UrlShortener::shortToInt("b"); 
Run Code Online (Sandbox Code Playgroud)

编辑

对于大量的情况,它不起作用。您应该将此版本(与 bcmath http://www.php.net/manual/en/book.bc.php一起使用)用于非常大的数字:

final class UrlShortener {

    private static $charfeed = Array(
    'a','A','b','B','c','C','d','D','e','E','f','F','g','G','h','H','i','I','j','J','k','K','l','L','m',
    'M','n','N','o','O','p','P','q','Q','r','R','s','S','t','T','u','U','v','V','w','W','x','X','y','Y',
    'z','Z','0','1','2','3','4','5','6','7','8','9');

    public static function intToShort($number) {
        $need = count(self::$charfeed);
        $s = '';

        do {
            $s .= self::$charfeed[bcmod($number, $need)];
            $number = floor($number/$need);
        } while($number > 0);

        return $s;
    }

    public static function shortToInt($string) {
        $num = 0;
        $need = count(self::$charfeed);
        $length = strlen($string);

        for($x = 0; $x < $length; $x++) {
            $key = array_search($string[$x], self::$charfeed);
            $value = $key * bcpow($need, $x);
            $num += $value;
        }

        return $num;
    }
}
$original = 131569877435989900;
$short = UrlShortener::intToShort($original);
echo $short;
echo '<br/>';
$result = UrlShortener::shortToInt($short);
echo $result;
echo '<br/>';
echo bccomp($original, $result);
Run Code Online (Sandbox Code Playgroud)

如果这里缺少某些内容,请告诉我,因为这只是我的库中的一个片段(我不想在这里插入整个内容)

内格拉