http://qs1969.pair.com?node_id=124817


in reply to Re: One-liner ascii/bin
in thread One-liner ascii/bin

All the pieces were there in the thread. I simply rearranged them...
#!/usr/bin/perl -wT use strict; my $bin = ascii2bin('Rolf'); my $ascii = bin2ascii($bin); print "bin => $bin\n"; print "ascii => $ascii\n"; sub ascii2bin { my $ascii = shift; my $bin = join '', map {sprintf "%08b", ord($_)} split //, $ascii; return $bin; } sub bin2ascii { my $bin = shift; my $ascii = join '', map {chr(oct"0b$_")} $bin =~ /(\d{8})/g; return $ascii; } =OUTPUT bin => 01010010011011110110110001100110 ascii => Rolf

Or, as one-liners.....

perl -le 'print join"",map{sprintf"%08b",ord($_)}split//,pop' Rolf perl -le 'print join"",map{chr(oct"0b$_")}pop=~/(\d{8})/g' 01010010011 +011110110110001100110

-Blake

Replies are listed 'Best First'.
Re: Re: Re: One-liner ascii/bin
by I0 (Priest) on Nov 13, 2001 at 11:25 UTC
    perl -e 'print unpack"B*",shift' Rolf
    perl -e 'print pack"B*",shift' 01010010011011110110110001100110
      Nice. For some reason I thought this approach had been suggested and rejected by Rolf but I misunderstood which part he objected to. These are much cleaner than the ones I came up with above.

      -Blake

      Hi, You are so veeery close, only that I get: Can't find string terminator "'" anywhere before EOF at -e line 1.

        Hi, You are so veeery close, only that I get: Can't find string terminator "'" anywhere before EOF at -e line 1. : Rolf

        It appears you are using CMD or COMMAND in Windows for your command-line interpretor, which doesn't know what to do with the quotes. Change I0's one-liner to this:

        perl -e "print unpack qq(B*),shift" Rolf

        ... and it will work.

        mkmcconn
        (or use cygwin, instead)

Re: Re: Re: One-liner ascii/bin
by Rolf (Novice) on Nov 12, 2001 at 17:59 UTC
    Hi, You are getting a lot closer now. (With the last two onliners.) I get a "Can't find string terminator "'" anywhere before EOF at -e line 1." when trying them. But they do look a bit like the ones I lost. Regards Rolf
      I double checked them and they work fine for me under perl 5.6.1 and unix. I did a quick test with perl 5.05_003 and they didn't work, but I didn't get the error message you're seeing. (looks like sprintf got smarter in the newer perls)

      -Blake

      Hi, I use perl, v5.6.1 built for MSWin32-x86-multi-thread Regards Rolf