in reply to Convert ASCII string to 7-bit binary string

c:\@Work\Perl\monks>perl -wMstrict -le "my $out; ;; $out .= reverse for unpack '(b7)*', '4B3A'; print qq{'$out'}; " '0110100100001001100111000001'


Give a man a fish:  <%-{-{-{-<

Replies are listed 'Best First'.
Re^2: Convert ASCII string to 7-bit binary string
by johngg (Canon) on Oct 28, 2015 at 11:52 UTC

    A slight variant that unpacks in the right order and drops the reverse for the expense of a second unpack inside a map.

    $ perl -Mstrict -Mwarnings -E ' my $out; $out .= $_ for map { unpack q{xA7}, $_ } unpack q{(B8)*}, q{4B3A}; say $out;' 0110100100001001100111000001 $

    Not as succinct but possibly slightly easier to work out what is going on because it is not immediately clear that your b7 format will drop the last (most significant) bit before you reverse the bits into the correct order.

    Cheers,

    JohnGG

      Inspired by kennethk's second approach above, this avoids the reversible complexity of either  '(B8)*' or  '(b7)*' in favor of  'C*' simplicity:

      c:\@Work\Perl\monks>perl -wMstrict -le "my $out; $out .= sprintf '%07b', $_ for unpack 'C*', '4B3A'; print qq{'$out'}; " '0110100100001001100111000001'


      Give a man a fish:  <%-{-{-{-<

Re^2: Convert ASCII string to 7-bit binary string
by Anonymous Monk on Oct 30, 2015 at 22:52 UTC
    why do you reverse?

      Because the  b7 unpack template that drops the most significant bit of the converted character also produces the binary digits in little-endian order. The OPer wants them in big-endian (i.e., most significant binary digit on the left) order, hence the 7-character sub-string must be reversed before being appended to the  $out string. Try it without reverse and see what you get.


      Give a man a fish:  <%-{-{-{-<