Skip to content

Instantly share code, notes, and snippets.

@mouse-reeve
Created May 27, 2014 05:25
Show Gist options
  • Save mouse-reeve/feeafe664f5c2b8fdfdc to your computer and use it in GitHub Desktop.
Save mouse-reeve/feeafe664f5c2b8fdfdc to your computer and use it in GitHub Desktop.
Converts a number to a negative base (between -2 and -10). Negadecimal, for example, or negabinary. http://en.wikipedia.org/wiki/Negative_base
function toNegativeBase(number, radix) {
if (radix > -2 || radix < -10) {
throw 'invalid radix';
}
var result = 0;
while (number != 0) {
var exp = number > 0 ? 0 : 1;
var sum = 0;
while (Math.abs(sum) < Math.abs(number)) {
sum += (-radix-1) * Math.pow(radix, exp);
exp += 2;
}
exp -= 2;
var digit = Math.floor(number/Math.pow(radix, exp));
digit = digit ? digit : 1;
number -= digit * Math.pow(radix, exp);
result += digit * Math.pow(10, exp);
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment