Skip to content

Instantly share code, notes, and snippets.

@lamchau
Created May 12, 2016 01:30
Show Gist options
  • Save lamchau/2294bf2e9dfb9068c6719bcfc3c06ecf to your computer and use it in GitHub Desktop.
Save lamchau/2294bf2e9dfb9068c6719bcfc3c06ecf to your computer and use it in GitHub Desktop.
function convert_to(n, base) {
if (base < 2 || base > 16) {
throw new Error("Invalid base '" + base + "'. Base must be >= 2 or <= 16");
}
if (n === 0) {
return 0;
}
var length = Math.floor(Math.log10(n) / Math.log10(base)) + 1;
var result = Array.apply(null, Array(length));
var remainder = n;
for (var i = length; i > 0; --i) {
result[i] = Math.floor(remainder % base);
remainder /= base;
}
return result.join("");
}
function convert_from(str, base) {
if (base < 2 || base > 16) {
throw new Error("Invalid base '" + base + "'. Base must be >= 2 or <= 16");
}
var result = 0;
var length = str.length;
for (var i = length; i > 0; --i) {
var value = +str.charAt(length - i);
result += (value * Math.pow(base, i - 1));
}
return result;
}
function test_to(number, base, expected) {
var actual = convert_to(number, base);
var message = "should convert 'number=" + number + ", base=" + base + "' to '" + expected + "'";
if (actual === expected) {
console.log(" ok:", message);
} else {
console.log("fail:", message + " (actual: " + actual + ")");
}
}
function test_from(str, base, expected) {
var actual = convert_from(str, base);
var message = "should convert 'str=" + str + ", base=" + base + "' to '" + expected + "'";
if (actual === expected) {
console.log(" ok:", message);
} else {
console.log("fail:", message + " (actual: " + actual + ")");
}
}
test_to(294, 2, "100100110");
test_to(294, 4, "10212");
test_to(357, 7, "1020");
test_to(357, 16, "165");
test_from("100100110", 2, 294);
test_from("10212", 4, 294);
test_from("1020", 7, 357);
test_from("165", 16, 357);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment