Peter
New Member
God
Posts: 6
|
Post by Peter on Aug 24, 2005 16:43:05 GMT
Two prototypes here which will convert string to binary and binary to string. <script type="text/javascript"> <!--
// String to binary String.prototype.str2bin = function(){ if(this){ var output = ""; for(s = 0; s < this.toString().length; s ++){ for(b = 128; b; b >>= 1){ output += (this.charCodeAt(s) & b)? "1" : "0"; } } return output; } }
// Binary to string String.prototype.bin2str = function(){ if(this){ var output = "", s = -8; e = 0; while((this.length % 8) == 0 && e != this.length){ output += String.fromCharCode(parseInt(this.substring(s += 8, e += 8), 2)); } return output; } }
//--> </script>Example of how to use them: // String to binary var oString = "Hello there!"; var binaryString = oString.str2bin(); alert(binaryString);
// Binary to string var oString2 = binaryString.bin2str(); alert(oString2);
|
|
chemdude
Full Member
2B || !2B
Posts: 228
|
Post by chemdude on Nov 9, 2005 0:45:14 GMT
Neat. Way to take advantage of OOP.
|
|