DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Base 10 To Binary Converter Javascript

09.08.2010
| 3952 views |
  • submit to reddit
        <b>Synopsis</b>
this is possibly the simplest toBinary function i've seen/written in javascript without using memory intensive power buiding until loops

<b>Purpose</b>
this function will take any numeric input (stripping out non numeric characters) and convert it into binary

function toBinary( n ) {
	n = n.replace(/[^0-9]/,'');
	if( !n || n == 0 ) return 0;
	//calculate the number of bits required to store the number
	var bits = Math.floor( Math.log( Math.pow( 2 , Math.ceil( Math.log( (Number( n ) +1 ) ) / Math.log( 2 ) ) ) ) / Math.log( 2 ) );
	var bitArray = new Array();
	var bitVal;
	var i;
	
	for( i = 0 ; i < bits ; i ++ ) {
		bitArray[i] = 0;
		//calculate the max value of this bit, make sure it starts as low as possible
		bitVal = Math.pow(2,bits-i-1);
		if( n >= bitVal) {
			bitArray[i] = 1;
			n = n - bitVal;
		}
	}
	
	return bitArray.join("");
}