Skip to content

Instantly share code, notes, and snippets.

@razashoaib
Last active December 16, 2017 10:17
Show Gist options
  • Save razashoaib/be0568570adb8152e50e7613d0daff46 to your computer and use it in GitHub Desktop.
Save razashoaib/be0568570adb8152e50e7613d0daff46 to your computer and use it in GitHub Desktop.
Convert decimal number to any base and map the result to pre-defined dictionary.
// Convert decimal number to desired base and convert the result to it's respective alphabets from the dictionary.
function convertBaseFromDecimal(number, desiredBase) {
var num = number;
var rem = 0;
var convertedNumber = [];
// NOTE: Modify dictionary if desiredBase != 5
var dict = {
0 : "a",
1 : "b",
2 : "c",
3 : "d",
4 : "e",
};
var resultStr = "";
while(num > 0) {
rem = num % desiredBase;
num = Math.floor(num / desiredBase);
convertedNumber.push(rem);
}
for(var i = (convertedNumber.length - 1); i >= 0 ; i--) {
resultStr += dict[convertedNumber[i]];
}
console.log(resultStr);
}
// Usage
function init() {
convertBaseFromDecimal(3232, 5); //Output will be 'baaebc'
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment