javascript base62 encode – decode

function base62_encode()

function(a,b,c){for(a=a!==+a||a%1?-1:a,b="";a>=0;a=Math.floor(a/62)||-1)b=String.fromCharCode(((c=a%62)>9?c>35?29:87:48)+c)+b;return b}

function base62_decode()

function(a,b,c,d){for(b=c=(a===(a+="")&&/^[a-z\d]+$/i.test(a))-1;d=a.charCodeAt(c++);)b=b*62+d-[,48,29,87][d>>5];return b}

140byt.es.

  • function (
      a, // positive base10 encoded integer
      b, // placeholder for result
      c  // placeholder for modulo
    ) {
    
      for (
        a = a !== +a || a % 1 ? -1 : a, b = ""; // if not a base10 integer, 'a' will be '-1'
                                                // for example, '.5 % 1 == .5' but '1 % 1 == 0'
        a >= 0; // also prevents the user to use negative base10 integers
        a = Math.floor(a / 62) || -1 // using a bitwise hack here will fail with great numbers
      )
    
        // a%62 -> 0-61
        // 0-9   | 36-61 | 10-35
        // 48-57 | 65-90 | 97-121
        // 0-9   | A-Z   | a-z
    
        b = String.fromCharCode(((c = a % 62) > 9 ? c > 35 ? 29 : 87 : 48) + c) + b;
    
      return b // will return either an empty or a base62-encoded string
    
    }

 

  • function (
      a, // base62 encoded string
      b, // placeholder for result
      c, // placeholder for iterator
      d  // placeholder for char code
    ) {
    
      for (
        b = c = ( // 'false - 1' will return '-1' and 'true - 1' will return '0'
          a === (/\W|_|^$/.test(a += "") || a) // tests if 'a' is a properly base62-encoded string and coerces it to one
        ) - 1; // so, 'b' and 'c' are initialized with either '-1' or '0'
    
        d = a.charCodeAt(c++); // if 'c' equals '-1', 'd' is 'NaN' which breaks the loop execution
      )
    
        b = b * 62 + d - [, 48, 29, 87][d >> 5]; // See comments : https://gist.github.com/1170594#gistcomment-48129
    
      return b // positive base10 integer or '-1' if 'a' is not a base62 encoded string
    
    }
This entry was posted in Code Snippets and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s