jdimpson (jdimpson) wrote,
jdimpson
jdimpson

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
foo

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 ($_ = <>) {
        chomp;
        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<>;
exit;
while ($_ = <>) {
        chomp;
        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.

*YAWN*
Tags: ascii, binary, binsp33k, notbinsp33k, one-liner, pack, perl, unpack
Subscribe
  • Post a new comment

    Error

    Anonymous comments are disabled in this journal

    default userpic

    Your IP address will be recorded 

  • 1 comment