Skip to content

Instantly share code, notes, and snippets.

@DimitrK
Last active September 24, 2018 22:34
Show Gist options
  • Save DimitrK/9eb25d21d3e4d96595fcbe97bf778ea3 to your computer and use it in GitHub Desktop.
Save DimitrK/9eb25d21d3e4d96595fcbe97bf778ea3 to your computer and use it in GitHub Desktop.
Convert to any base from base10. Returns the result into an array which you can later process further or user Array.join in order to get the final based number
function toBase(number, base) {
if (base <2) {
throw new Error("Base has to be greater than 2");
}
var basedNumberArray = [];
var divider = Math.floor(number / base);
var basedNumber = number % base;
var basedCode = getAsciiCap(basedNumber);
basedNumberArray.push(basedCode || basedNumber);
while (divider != 0) {
basedNumber = divider % base;
basedCode = getAsciiCap(basedNumber);
basedNumberArray.push(basedCode || basedNumber);
divider = Math.floor(divider / base);
}
return basedNumberArray.reverse();
}
function getAsciiCap(aNumber) {
var asciiCode = '';
var asciiOffset = aNumber - 10;
while(asciiOffset>=0) {
let asciiCapsBase = 65;
let asciiCapsTop = 95;
let ascii = asciiOffset + asciiCapsBase;
if (ascii > asciiCapsTop) {
ascii = asciiCapsTop;
asciiOffset -= asciiCapsTop - asciiCapsBase
} else {
asciiOffset = -1;
}
asciiCode += String.fromCharCode(ascii);
}
return asciiCode;
}
@DimitrK
Copy link
Author

DimitrK commented Dec 12, 2017

Convert to any base from base10. Returns the result into an array which you can later process further or user Array.join in order to get the final based number

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment