Rolf has asked for the wisdom of the Perl Monks concerning the following question:

Hi friends, I once had two one-liners which converted a string to bin and vice versa. But I lost them togeher with my HD and I am not any good at Perl. Any help would be appriciated. Rolf

Replies are listed 'Best First'.
Re (tilly) 1: One-liner ascii/bin
by tilly (Archbishop) on Nov 11, 2001 at 07:29 UTC
    What do you mean by bin?

    There are many possible things you could mean, and they have very different answers. For instance you could be looking for an encryption module, of which there are several on CPAN. Or you might be looking for pack and unpack. If you are on Windows try this:

    perl -ne "print unpack("B*", $_)" input_file > output_file
    (Use single quotes on Unix.)

    You can reverse it with:

    perl -ne "print pack("B*", $_)" input_file > output_file
    See pack, unpack, and perlrun for more.
Re: One-liner ascii/bin
by jj808 (Hermit) on Nov 11, 2001 at 09:25 UTC
    My assumption was that you wanted binary to decimal conversion. If so, try these:
    Binary to Decimal: perl -e 'for(split//,$ARGV[0]){$t+=$_;$t=$t<<1};$t=$t>>1;print "$t\n"' + 101010 Decimal to Binary: perl -e '$t=$ARGV[0];do{push@b,$t%2;$t=$t>>1}until($t==0);print revers +e"\n",@b' 42



      perl -e 'print oct"0b$ARGV[0]","\n"' 101010
      perl -e 'printf"%b\n",@ARGV' 42
Re: One-liner ascii/bin
by Rolf (Novice) on Nov 12, 2001 at 16:42 UTC
    I am sorry I am not able to express myself better. What I am trying to explain is this: I write something like Perl -e ... "Rolf" and it comes out like this: 01010010011011110110110001100110 and if I use the 01's as argument in another one-liner I get the output: Rolf Thank you for your efforts and sorry about me not explaining it better Regards Rolf
      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


        perl -e 'print unpack"B*",shift' Rolf
        perl -e 'print pack"B*",shift' 01010010011011110110110001100110
        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