peter
Guest
|
Two prototypes here which will convert string to binary and binary to string. 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; } }
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; } }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);
Last Edit: Nov 5, 2005 18:40:43 GMT by peter
|
|
|
|
questions: What's does the >> infront of the = sign, in the loop do? and What's charCodeAt and fromCharCode ?
|
|
|
peter
Guest
|
It's a bitwise operator. In this case it was the bitwise right shift operator. It's for shifting the bits by the number of columns specified. So... 2 = 0 0 0 0 0 0 1 0 2 >> 1 = 1 1 = 0 0 0 0 0 0 0 1 Another... 128 = 1 0 0 0 0 0 0 0 128 >> 2 = 32 32 = 0 0 1 0 0 0 0 0 32 >> 5 = 1
Last Edit: Nov 6, 2005 16:57:48 GMT by peter
|
|
|
|
After reading some stuff at Wikipedia, I understand now
|
|
|
|
I'm still confused, but I think I get it. It basically converts it to that base, with that number. Right?
|
|
|
|
|
There are 2 operators, right shift and left shift.
say we have this number: 11100010
What the left shift operator would do is, take the numbers of the left side (how many you tell it to) and removes it, then adds the same amount of zero's to the right side.
11100010 << 2 = 1000100
so it takes 2 numbers from the left, removes them and puts 2 zero's to the right side. With the right shift operator it would look like this:
11100010 >> 2 = 001000
It's the same as the left side, only now it takes the numbers from the right side and adds the zero's from the left side.
|
|
|
|
Oh!....
|
|
|
|