Created
August 23, 2016 11:30
-
-
Save JanneSalokoski/4763e76d7d3aa9db32719d8e3e5dabf6 to your computer and use it in GitHub Desktop.
base64.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let characters = "0123456789abcdefghijklmopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/" | |
function encode64(num) | |
{ | |
let BASE = 64; //Define the base to convert num to | |
let string = ""; | |
let i = 0; | |
let cont = true; | |
while (cont) | |
{ | |
//If num is smaller than base ** (iteration + 1), we can continue | |
if (num < Math.pow(BASE, i + 1)) | |
{ | |
let sum = 0; | |
let floor = Math.floor(num / Math.pow(BASE, i)); // Drop the decimal part from num / base ** iteration | |
let sum = Math.pow(64, i) * floor; // Multiply result by base ** iteration | |
let a = i; | |
while (i >= 0) | |
{ | |
floor = Math.floor(num / Math.pow(BASE, i)); | |
floor2 = Math.floor((num - sum)) / Math.pow(BASE, i); | |
sum = Math.pow(BASE, i) * floor; | |
// If a == i, append characters[floor], otherwise characters[floor2], to string | |
(a == i) ? string += characters[floor] : string += characters[floor2]; | |
i--; | |
} | |
cont = false; // If i < 0 we want don't continue | |
} | |
i++; | |
} | |
return string; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment