Last active
November 26, 2015 14:12
-
-
Save uda/6064226218ec0462b800 to your computer and use it in GitHub Desktop.
JavaScript base conversion that provides up to 64 base conversion. Based on http://www.javascripter.net/faq/convert3.htm, read more: http://en.wikipedia.org/wiki/Radix
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Examples: | |
* var R = Radix(2); | |
* R.to(10); will result in "1010" | |
* R.from("1010"); sill result in 10 | |
* var R = Radix(16); | |
* R.to(10); will result in "a" | |
* R.from("a"); sill result in 10 | |
* | |
* Notice: | |
* Safe integer range to use: -9007199254740991 - 9007199254740991 | |
* Read more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER | |
*/ | |
var Radix = function(Base) { | |
var Chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$~".substr(0, Base); | |
var Convert = { | |
to: function (Number) { | |
var HexN = "", AbsInt = Math.floor(Math.abs(Number)), R; | |
while (true) { | |
R = AbsInt % Base; | |
HexN = Chars.charAt(R) + HexN; | |
AbsInt = (AbsInt - R) / Base; | |
if (AbsInt == 0) { | |
break; | |
} | |
} | |
return ((Number < 0) ? "-" + HexN : HexN); | |
}, | |
from: function (String) { | |
var Number = 0, | |
String = String.toString(), | |
Negative = String[0] == "-"; | |
for (var i = 0; i < String.length; i += 1) { | |
if (Negative && !i) continue; | |
Index = Chars.indexOf(String[i]); | |
if (Index == -1) { | |
throw "Input error: The source string does not match the Base conversion."; | |
} | |
Number = Index + (Number * Base); | |
} | |
return Negative ? parseInt(Negative + Number) : Number; | |
}, | |
encode: Convert.to, | |
decode: Convert.from | |
}; | |
return this.Convert; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice. What about fromRadix(key)?