Base conversion in JavaScript
I just realized recently that you can convert between number bases in JavaScript using the built in method Object.prototype.toString() and parseInt().
Math.base = function(n, to, from) {
return parseInt(n, from || 10).toString(to);
}
For example, to convert from decimal to hex, or hex to decimal:
// convert the decimal 10 to hex
Math.base(10, 16); // 'a'
// convert the hex 'a' to decimal
Math.base('a', 10, 16); // 10
// or
Math.base(0xA, 10); // 10
Or from hex or dec to binary:
// convert the decimal 10 to binary
Math.base(10, 2); // '1010'
// convert the hex 'a' to decimal
Math.base('a', 2, 16); // 1010
This should work for bases between 2 and 36. ie: the number of characters from 0-9a-z.
Edit: changed base() to Math.base() for better namespace
I’ve also added base conversion in PHP up to a radix of 255.
Related posts:
- Base conversion in PHP, Radix 255 Allows you to convert to any base between 2 and 255, effectively using all the ASCII characters. In order to...
- ASCII to Hex in JavaScript This JavaScript will add a method to the String object, that converts the ASCII string to a hex string consisting...
- Fun with JavaScript bookmarks Here are some random JavaScript sinippets I wrote for bookmarks. How they work is when you click the bookmark, the...
- JavaScript Regex match all characters JavaScript regular expressions (browser) do not have a modifier allowing the dot (.) to match all characters including the newline...