RSS
 

Convert Base 10 to Base 64 and vise versa using JavaScript

13 Jan

This is the way to convert base 10 (a decimal number) into a base 64 string and base 64 into a base 10, while the order of that base is as following:

0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-

Base 10 to Base 64

1
2
3
4
5
6
7
8
9
10
11
12
function base10_to_base64(num) {
    var order = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-";
    var base = order.length;
    var str = "", r;
    while (num) {
        r = num % base
        num -= r;
        num /= base;
        str = order.charAt(r) + str;
    }
    return str;
}

Base 64 to Base 10

1
2
3
4
5
6
7
8
9
10
11
12
function base64_to_base10(str) {
    var order = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-";
    var base = order.length;
    var num = 0, r;
    while (str.length) {
        r = order.indexOf(str.charAt(0));
        str = str.substr(1);
        num *= base;
        num += r;
    }
    return num;
}

Live Test

Base 10:
Base 64:


Good luck!

 

Tags: , , , , , , , , ,

Leave a Reply