Created
March 19, 2013 01:28
-
-
Save jonathanmarvens/5192828 to your computer and use it in GitHub Desktop.
Convert an integer to its binary representation using a simple stack-based algorithm.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function integer_to_binary ( integer ) { | |
if ( ( toString.call( integer ) !== '[object Number]' ) || ( integer < 0 ) ) { | |
return null; | |
} else if ( integer === 0 ) { | |
return '0'; | |
} else { | |
var stack = []; | |
// var STACK_CAPACITY = 8; | |
while ( integer > 0 ) { | |
var bits = ( integer % 2 ); | |
if ( typeof STACK_CAPACITY !== 'undefined' && STACK_CAPACITY !== null ) { | |
if ( ( toString.call( STACK_CAPACITY ) === '[object Number]' ) && ( STACK_CAPACITY > 0 ) ) { | |
if ( stack.length === STACK_CAPACITY ) { | |
throw new Error( 'Sorry. The bit stack cannot handle any more than ' + STACK_CAPACITY + ' element' + ( ( STACK_CAPACITY === 1 ) ? '' : 's' ) + '.' ); | |
} | |
} | |
} | |
stack.push( bits ); | |
integer = Math.floor( ( integer / 2 ) ); | |
} | |
var binary_string = ''; | |
while ( stack.length > 0 ) { | |
binary_string += stack.pop(); | |
} | |
return binary_string; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment