Simple Integer to Base62

Would anyone have a bit of Xojo code to convert an integer into Base 62? I found this bit of javascript at vmix url that does what I need, but I’m NO expert in JS and it makes my head hurt.

Anyone able to quickly translate this into Xojo for me? I’d surely appreciate it!

    var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    var alphas = chars.split('');

function callid2shorturl(callid) {
    var count = parseInt(callid);
    var div = alphas.length;
    var result = "";

    if (!Number.isInteger(count)) {
        return "Invalid number!";
    }

    var run = 16;
    var mod, quot = 0;
    while(run--) {
        mod = count % div;
        quot = Math.floor(count / div);
        result = alphas[mod] + result;
        console.log("[" + result + "] CNT: " + count + " / " + div + " = " + quot + " % " + mod);
        if (quot == 0) {
            run = 0;
        }
        count = quot;
    }
    return result;
}

There are many examples already on the forum. I recall functions to convert from any base to any base up to 36, for 62 just add the extra chars.

This site was pretty good at explaining, with a simpler example in Golang:
https://medium.com/analytics-vidhya/base-62-text-encoding-decoding-b43921c7a954

I threw this together, only tested a couple of values though. Use at your own risk. intVal is the integer input.

var encoded as Text = ""
var characterSet as Text = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
while intVal > 0
  var r as Integer = intVal mod 62
  intVal = intVal / 62
  encoded =  characterSet.mid(r,1) + encoded
wend

MessageBox encoded
1 Like

Thank you!! This helps so much!

1 Like
Forum for Xojo Programming Language and IDE. Copyright © 2021 Xojo, Inc.