Skip to content

Instantly share code, notes, and snippets.

@flesch
Forked from 140bytes/LICENSE.txt
Created August 22, 2012 21:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save flesch/3429545 to your computer and use it in GitHub Desktop.
Save flesch/3429545 to your computer and use it in GitHub Desktop.
str2seq: Text to Binary

str2seq

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>
@atk
Copy link

atk commented Aug 24, 2012

Forgot one backslash:

function c(a,b){return++b?(256+a.charCodeAt()).toString(2).slice(1):a.replace(/[\x00-\xff]/g,c)}

@tsaniel
Copy link

tsaniel commented Aug 24, 2012

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?

@atk
Copy link

atk commented Aug 24, 2012

Hi, @tsaniel. Nice one, as always. The notification doesn't work for me, too.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment