encode a big integer to base62

前端 未结 1 885
暖寄归人
暖寄归人 2021-01-23 09:33

I need to create unique referral codes. To make each Referral code unique I am trying to do something like below.

const stringVal = `${currentTimestamp}$         


        
相关标签:
1条回答
  • 2021-01-23 10:08

    FWIW, the following are two helper functions that convert a BigInt to a desired base and vice versa...

    var digits = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    
    function bigint2base( x, baseDigits ) {
    
      let base = BigInt( baseDigits.length );
      let result = '';
      
      while ( 0 < x ) {
        result = baseDigits.charAt( Number( x % base ) ) + result;
        x = x / base;
      }
        
      return result || '0';
      
    }
    
    
    function base2bigint( x, baseDigits ) {
    
      let base = BigInt( baseDigits.length ); 
      let result = 0n;
      
      for ( let i = 0; i < x.length; i++ ) {
        result = result * base + BigInt( baseDigits.indexOf( x.charAt( i ) ) );
      }
      
      return result;
    }
    
    console.log( `BigInt 158632196111710003n to base62 ( '${digits}' )...`);
    base62val = bigint2base( 158632196111710003n, digits );
    console.log( base62val );
    
    console.log( `Converted back to BigInt is...` );
    console.log( base2bigint( base62val, digits ).toString() );
    
    console.log('');
    console.log( `BigInt 31957108571341948394931814703184314387417471347093174n to base62 ( '${digits}' )...`);
    base62val = bigint2base( 31957108571341948394931814703184314387417471347093174n, digits );
    console.log( base62val );
    
    console.log( `Converted back to BigInt is...` );
    console.log( base2bigint( base62val, digits ).toString() );

    Hope this helps...

    0 讨论(0)
提交回复
热议问题