用于URL缩短的十六进制到基数62的转换

hex to base 62 conversion for URL shortening

本文关键字:转换 十六进制 URL 用于      更新时间:2023-09-26

我希望将24个字符长的十六进制mongoDB对象ID转换为base62格式,这样URL就更短了。我不想从十六进制转换为整数,然后再转换为base62。有没有代码已经做到了这一点?

这可以在任意碱基/字母之间转换。

如果你在URL中使用Base58,可以考虑使用它,因为人们可以更容易地输入,而不会混淆长相相似的字符。

因为64是16的倍数,所以最好的方法是使用查找表。任何三个十六进制数字都由两个以64为基数的数字表示,因此每个查找表中需要16³=64²=4096个条目才能实现这一点。

我有一个perl脚本,它将在https://gist.github.com/3730664

我还有一个生成和转换函数的完整实现(同样是在perl中),我正在使用这些函数来转换MongoDB ID,如果有用的话,请告诉我。

编辑:我已经将我正在使用的完整实现添加到上面链接的要点中。

节点int编码器执行此

npm install int-encoder
var en = require('int-encoder');
//simple integer conversion
en.encode(12345678); // "ZXP0"
en.decode('ZXP0'); // 12345678
//convert big hex number using optional base argument
en.encode('e6c6b53d3c8160b22dad35a0f705ec09', 16); // 'hbDcW9aE89tzLYjDgyzajJ'
en.decode('hbDcW9aE89tzLYjDgyzajJ', 16); // 'e6c6b53d3c8160b22dad35a0f705ec09'

LZ字符串

你可以使用lz字符串来压缩你的字符串。

我建议您使用他们的函数compressToBase64进行压缩,使用decompressFromBase64进行解压缩。

你可以使用他们的常规压缩&解压缩功能,但你的压缩字符串可能会有各种奇怪的汉字在里面。

你可以在这里找到关于如何下载和使用lz字符串的指南。

请参阅下面用C#编写的代码,将逻辑转换为您想要的任何语言。您还可以更改名称空间中的顺序或字符,使转换对您来说是唯一的。

public static class ShortCodes
{
    private static Random rand = new Random();
    // You may change the "shortcode_Keyspace" variable to contain as many or as few characters as you
    // please.  The more characters that aer included in the "shortcode_Keyspace" constant, the shorter
    // the codes you can produce for a given long.
const string shortcode_Keyspace = "abcdefghijklmnopqrstuvwxyz0123456789";
    // Arbitrary constant for the maximum length of ShortCodes generated by the application.
const int shortcode_maxLen = 12;

    public static string LongToShortCode(long number)
    {
        int ks_len = shortcode_Keyspace.Length;
        string sc_result = "";
        long num_to_encode = number;
        long i = 0;
        do
        {
            i++;
            sc_result = shortcode_Keyspace[(int)(num_to_encode % ks_len)] + sc_result;
            num_to_encode = ((num_to_encode - (num_to_encode % ks_len)) / ks_len);
        }
        while (num_to_encode != 0);
        return sc_result;
    }

    public static long ShortCodeToLong(string shortcode)
    {
        int ks_len = shortcode_Keyspace.Length;
        long sc_result = 0;
        int sc_length = shortcode.Length;
        string code_to_decode = shortcode;
        for (int i = 0; i < code_to_decode.Length; i++)
        {
            sc_length--;
            char code_char = code_to_decode[i];
            sc_result += shortcode_Keyspace.IndexOf(code_char) * (long)(Math.Pow((double)ks_len, (double)sc_length));
        }
        return sc_result;
    }
}