Skip to content

Instantly share code, notes, and snippets.

@barbier
Last active July 12, 2016 03:14
Show Gist options
  • Save barbier/d052d81381c45768d653d0670d3a3715 to your computer and use it in GitHub Desktop.
Save barbier/d052d81381c45768d653d0670d3a3715 to your computer and use it in GitHub Desktop.
Base converter
function Stack() {
var items = [];
this.push = function(element) {
items.push(element);
}
this.pop = function() {
return items.pop();
}
this.peek = function() {
return items[items.length-1];
}
this.isEmpty = function() {
return items.length == 0;
}
this.size = function() {
return items.length;
}
this.clear = function() {
items = [];
}
this.print = function() {
console.log(items.toString());
}
}
function baseConverter(decNumber, base) {
var remainderStack = new Stack(),
remainder,
baseString = '',
digits = '0123456789ABCDEF';
while (decNumber > 0) {
remainder = Math.floor(decNumber % base);
remainderStack.push(remainder);
decNumber = Math.floor(decNumber / base);
}
while (!remainderStack.isEmpty()) {
baseString += digits[remainderStack.pop()];
}
return baseString;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment