Return to Snippet

Revision: 115
at June 30, 2006 09:21 by Zikes


Initial Code
// 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;
}

Initial URL

                                

Initial Description
This is a quick & easy system for changing the base of any number.

Initial Title
Base Conversion

Initial Tags
javascript

Initial Language
JavaScript