`Java has toBinaryString method for Integer class. Javascript doesn't have this method for Number class. Here is the implemenation for 32 bit integers. Number.prototype.isInteger = function() { return (this.toString().search(/^-?[0-9]+$/) == 0); } Number.prototype.toBinaryString = function() { if(!this.isInteger()) return ''; var num = this.valueOf(); var temp = Math.pow(2, 31); if(num > ( temp * 2 - 1) || num < -temp ) return ''; var arr = new Array(32); for(var i = 31; i >= 0; --i){ arr[i] = (num & 1); num = num>>>1; } return arr.join(''); } On the reverse to convert binary string to integer String.prototype.binaryStringToInteger = function(signed) { var val = parseInt(this.valueOf(), 2); if(signed && parseInt(this[0]) ) { // negative num return val - Math.pow(2, this.length) ; } return val; } `

# Javascript toBinaryString and binaryStringToInteger

Advertisements