Bash – ASCII to Binary and Binary to ASCII conversion tools

asciibashbinary

Which is a good tool to convert ASCII to binary, and binary to ASCII?

I was hoping for something like:

$ echo --binary "This is a binary message"
01010100 01101000 01101001 01110011 00100000 01101001 01110011 00100000 01100001 00100000 01100010 01101001 01101110 01100001 01110010 01111001 00100000 01101101 01100101 01110011 01110011 01100001 01100111 01100101

Or, more realistic:

$ echo "This is a binary message" | ascii2bin
01010100 01101000 01101001 01110011 00100000 01101001 01110011 00100000 01100001 00100000 01100010 01101001 01101110 01100001 01110010 01111001 00100000 01101101 01100101 01110011 01110011 01100001 01100111 01100101

And also the reverse:

$ echo "01010100 01101000 01101001 01110011 00100000 01101001 01110011 00100000 01100001 00100000 01100010 01101001 01101110 01100001 01110010 01111001 00100000 01101101 01100101 01110011 01110011 01100001 01100111 01100101" | bin2ascii
This is a binary message

PS: I'm using bash

PS2: I hope I didn't get the wrong binary

Best Answer

$ echo AB | perl -lpe '$_=unpack"B*"'
0100000101000010
$ echo 0100000101000010 | perl -lpe '$_=pack"B*",$_'
AB
  • -e expression evaluate the given expression as perl code
  • -p: sed mode. The expression is evaluated for each line of input, with the content of the line stored in the $_ variable and printed after the evaluation of the expression.
  • -l: even more like sed: instead of the full line, only the content of the line (that is, without the line delimiter) is in $_ (and a newline is added back on output). So perl -lpe code works like sed code except that it's perl code as opposed to sed code.
  • unpack "B*" works on the $_ variable by default and extracts its content as a bit string walking from the highest bit of the first byte to the lowest bit of the last byte.
  • pack does the reverse of unpack. See perldoc -f pack for details.

With spaces:

$ echo AB | perl -lpe '$_=join " ", unpack"(B8)*"'
01000001 01000010
$ echo 01000001 01000010 | perl -lape '$_=pack"(B8)*",@F'
AB

(it assumes the input is in blocks of 8 bits (0-padded)).

With unpack "(B8)*", we extract 8 bits at a time, and we join the resulting strings with spaces with join " ".