Log in

No account? Create an account
12 April 2008 @ 12:29 pm
binsp33k: Convert ascii input to binary  
There's no good use for these, and I can't remember why I wrote them.   There are two of them, one to convert its ascii input into a string of 1s and 0s (and spaces) equal to the binary representation of the input, and the other to reverse the process.  You'd invoke it like this:

$  echo foo | binsp33k
01100110 01101111 01101111

$ echo foo | binsp33k | notbinsp33k

binsp33k is dated 2003-06-08 and notbinsp33k is dated 2003-06-10.  While preparing for this post, I was surprised there are two days between them.  As you'll see, I came up with (or possibly stumbled across) a different way to implement notbinsp33k.

BEGIN binsp33k

#!/usr/bin/perl -w
while ($_ = <>) {
        my $o = unpack q/B*/, $_;
        $o =~ s/([01]{8})/$1 /g;
        print $o . "\n";

END binsp33k

For those of you still paying attention, you'll notice this is a Perl script, not a shell script.  I could have used the "-n" flag to perl--not sure why I didn't.  The heart of the program is the unpack() call.  It pretty much does all the work; I use the following substitution expression to split the output into 8-character groups for easier human reading.

BEGIN notbins33k

#!/usr/bin/perl -w
s/(\d+)\s?/pack B8,$1/ge&&print for<>;
while ($_ = <>) {
        my $o = '';
        while (s/([01]{8})\s+//) {
                $o .= pack q/B*/, $1;
        print $o . "\n";

END notbinsp33k

You can see there are two implementations.  The one below the call to exit is the original, the one above is the more clever one-liner version.

notbinsp33k originally followed the same pattern as the as binsp33k. The outer while loop lets it read multiple lines of input, and the inner while loop handles each group of 8 1s and 0s.

The one-liner version does the same thing, although it's worth noting that the original version requires spaces between the bytes, whereas the one-liner can handle spaced or non-spaced input.  I'm pretty sure the original one could be modified to be as accepting.

I probably found the one-liner version somewhere else (or found a similar one-liner that I modified), because while I appreciate one-liner (something commonly done in Perl), I usually don't go out of my way to create them.  Perl's high expressivness is what makes one-liners so easy, but it doesn't mean you should do everything in one line.

jdimpsonjdimpson on May 28th, 2008 04:06 pm (UTC)
Questionably good use disocvered
I bought the Penny Arcade game, On the Rain-Slick Precipice of Darknes (http://www.playgreenhouse.com/), and in the game the FruitF*cker robots speak in binary (in their word balloons). This script converted their binary to ascii. I won't ruin the surprise, although what they say isn't all that surprising.