What's the best way to create a short hash, similar to what tiny Url does?

前端 未结 13 1324
被撕碎了的回忆
被撕碎了的回忆 2020-12-04 09:10

I\'m currently using MD5 hashes but I would like to find something that will create a shorter hash that uses just [a-z][A-Z][0-9]. It only needs to be around 5-

13条回答
  •  盖世英雄少女心
    2020-12-04 09:49

    You can decrease the number of characters from the MD5 hash by encoding them as alphanumerics. Each MD5 character is usually represented as hex, so that's 16 possible values. [a-zA-Z0-9] includes 62 possible values, so you could encode each value by taking 4 MD5 values.

    EDIT:

    here's a function that takes a number ( 4 hex digits long ) and returns [0-9a-zA-Z]. This should give you an idea of how to implement it. Note that there may be some issues with the types; I didn't test this code.

    char num2char( unsigned int x ){
        if( x < 26 ) return (char)('a' + (int)x);
        if( x < 52 ) return (char)('A' + (int)x - 26);
        if( x < 62 ) return (char)('0' + (int)x - 52);
        if( x == 62 ) return '0';
        if( x == 63 ) return '1';
    }
    

提交回复
热议问题