Convert ASCII
text to a Binary
string sequence.
str2seq("Hello!");
This will return "010010000110010101101100011011000110111100100001"
See also: seq2str
.
function str2seq( | |
a, // the text that you want to encode | |
b, // placeholder | |
c, // placeholder | |
d // placeholder | |
) { | |
for( | |
b = "", // start b out as an empty string that we'll add to | |
d = a.length; d--; // reverse loop through each character | |
) c = a.charCodeAt(d).toString(2), // Convert the character to binary | |
b = Array(9-c.length).join(0) // .toString won't have any of the leading 0's | |
+ c + b; // Add the leading zeros to the binary version, and add it in front of what we've already converted | |
return b | |
} |
function(a,b,c,d){for(b="",d=a.length;d--;)c=a.charCodeAt(d).toString(2),b=Array(9-c.length).join(0)+c+b;return b} |
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE | |
Version 2, December 2004 | |
Copyright (C) 2012 John Flesch <http://fles.ch/> | |
Everyone is permitted to copy and distribute verbatim or modified | |
copies of this license document, and changing it is allowed as long | |
as the name is changed. | |
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE | |
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION | |
0. You just DO WHAT THE FUCK YOU WANT TO. |
{ | |
"name": "str2seq", | |
"description": "Convert ASCII text to a binary string sequence.", | |
"keywords": ["encode"] | |
} |
<!DOCTYPE html> | |
<title>str2seq</title> | |
<pre>Expected value: 010010000110010101101100011011000110111100100001 | |
Actual value: <span id="ret"></span></pre> | |
<script> | |
var myFunction = function(a,b,c,d){for(b="",d=a.length;d--;)c=a.charCodeAt(d).toString(2),b=Array(9-c.length).join(0)+c+b;return b} | |
document.getElementById( "ret" ).innerHTML = myFunction("Hello!") | |
</script> |
This will not replace control characters (like carriage return or new line). Slightly longer, working version (I replaced slice(-8) with slice(1)):
function f(a,b){return++b?(256+a.charCodeAt()).toString(2).slice(1):a.replace(/[\x00-xff]/g,f)}
Forgot one backslash:
function c(a,b){return++b?(256+a.charCodeAt()).toString(2).slice(1):a.replace(/[\x00-\xff]/g,c)}
Try this
function f(a,b){return++b?(256+a.charCodeAt()).toString(2).slice(1):a.replace(/[^]/g,f)}
By the way, why can't I receive notification when someone's replying?
Hi, @tsaniel. Nice one, as always. The notification doesn't work for me, too.
What about this?
function f(a,b){return++b?(1e9+a.charCodeAt().toString(2)).slice(-8):a.replace(/./g,f)}