Javascript toBinaryString and binaryStringToInteger

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; }

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s