/ Published in: JavaScript
This is a quick & easy system for changing the base of any number.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
// Sample usage for decimal to hex: base(255, '0123456789ABCDEF') == 'FF' // Common conversions such as above are easy to wrap with a helper function to speed use function base(dec,base){ var len=base.length; var ret=''; while(dec>0){ ret = base.charAt(dec%len) + ret; dec = Math.floor(dec/len); } return ret; } // Converts from nondecimal string to decimal // Example: unbase('FF', '0123456789ABCDEF') == 255 function unbase(num, base){ var len=base.length; var ret=0; for(var x=1;num.length>0;x*=len){ ret += base.indexOf(num.charAt(num.length-1)) * x num = num.substr(0,num.length-1); } return ret; }