Base Conversor //JavaScript Repository
Description
Generic base conversor, accepts as parameter a charset to be used in the conversion.
Created: 2005.10.02
Created: 2005.10.02
Code (Download)
//+ Carlos R. L. Rodrigues
//@ http://jsfromhell.com/number/base-conversor [rev. #1]
Number.prototype.toBase = function(b, c){
var s = "", n = this;
if(b > (c = (c || "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz").split("")).length || b < 2) return "";
while(n)
s = c[n % b] + s, n = Math.floor(n / b);
return s;
};
String.prototype.parseInt = function(b, c){
var s = 0, n, l = (n = this.split("")).length, i = 0;
if(b > (c = c || "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz").length || b < 2) return NaN;
while(l--)
s += c.indexOf(n[i++]) * Math.pow(b, l);
return s;
};
Example (Example)
<script type="text/javascript">
//<![CDATA[
var c = "aZd292KVA_$*/+=3918f5";
document.write(
"<h2>Default Charset</h2><h3>Number.toBase</h3>",
"(255).toBase(2) = ", (255).toBase(2), "<br />",
"(255).toBase(8) = ", (255).toBase(8), "<br />",
"(255).toBase(10) = ", (255).toBase(10), "<br />",
"(255).toBase(16) = ", (255).toBase(16), "<br />",
"<h3>String.parseInt</h3>",
"\"11111111\".parseInt(2) = ", "11111111".parseInt(2), "<br />",
"\"377\".parseInt(8) = ", "377".parseInt(8), "<br />",
"\"255\".parseInt(10) = ", "255".parseInt(10), "<br />",
"\"FF\".parseInt(16) = ", "FF".parseInt(16), "<br />",
"<h2>Different Charset</h2>",
"Charset = ", c, "<h3>Number.toBase</h3>",
"(12345678).toBase(21, Charset) = ", (12345678).toBase(21, c), "<br />",
"<h3>String.parseInt</h3>",
"\"2a$Z3_\".parseInt(21, Charset) = ", "2a$Z3_".parseInt(21, c), "<br />"
);
// x.base, charSet)
//]]>
</script>
Help
Methods
- Number.toBase(base: Integer, [charset: String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"]): String
-
Encodes an integer number into string.
- base
- base that will be used to encode the number (from 2 to charset.length)
- charset
- set of characters that will be used in the encoding
- String.parseInt(base: Integer, [charset: String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"]): Integer
-
Decodes a string into an integer number.
- base
- base that will be used to decode the number (from 2 to charset.length)
- charset
- set of characters that will be used in the decoding
Rank (Votes: 13)
4.15