Skip to content

Instantly share code, notes, and snippets.

@flesch
Forked from 140bytes/LICENSE.txt
Created August 22, 2012 21:29
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/3429574 to your computer and use it in GitHub Desktop.
Save flesch/3429574 to your computer and use it in GitHub Desktop.
seq2str: Binary to Text

seq2str

Convert a Binary string sequence to ASCII text.

seq2str("010010000110010101101100011011000110111100100001");

or (with spaces)

seq2str("01001000 01100101 01101100 01101100 01101111 00100001");

Both will return "Hello!"

See also: str2seq.

function seq2str(
a // binary sequence
){
return a.replace(
/(.{1,8}\s?)/g, // Find every 8 characters (and maybe a space)
function(b){ // Convert these 8 characters to text
return String.fromCharCode( // Convert character code to text
parseInt(b,2) // Convert from base 2 to base 10
)
}
)
}
function(a){return a.replace(/(.{1,8}\s?)/g,function(b){return String.fromCharCode(parseInt(b,2))})}
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": "seq2tr",
"description": "Convert a binary string sequence to ASCII text.",
"keywords": ["encode"]
}
<!DOCTYPE html>
<title>seq2str</title>
<pre>Expected value: Hello!
Actual value: <span id="ret"></span></pre>
<script>
var myFunction = function(a){return a.replace(/(.{1,8}\s?)/g,function(b){return String.fromCharCode(parseInt(b,2))})}
document.getElementById( "ret" ).innerHTML = myFunction("01001000 01100101 01101100 01101100 01101111 00100001")
</script>
@atk
Copy link

atk commented Aug 24, 2012

Same applies here (plus you can lose the matches, as the first full matched expression will be the first argument anyway:

function f(a,b){return++b?String.fromCharCode(parseInt(a,2)):a.replace(/.{1,8}\s?/g,f)}

@tsaniel
Copy link

tsaniel commented Aug 24, 2012

Maybe I missed something, but why {1,8} instead of just{8}?

@atk
Copy link

atk commented Aug 24, 2012

It still works in case one removed the leading zeros but added the byte padding in form of spaces, for example "1001000 1100101 1101100 1101100 01101111 100001".

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