Over a million developers have joined DZone.

Base 10 To Binary Converter Javascript

·
Synopsis
this is possibly the simplest toBinary function i've seen/written in javascript without using memory intensive power buiding until loops

Purpose
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("");
}
Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}