Hello fellow monks

I have a sequence of bits that I want to convert back into actual values. I found a working algorithm, but there's probably an easier way to achieve what I want.

Input format: 0 and 1's in big-endian order. The number of bits may or may not equal multiples of 8.

Output format: Convert all groups of 8 into actual value, remaining bits must be kept. (Converted values can be any ASCII value, UTF-8 is not relevant.)

Sample script

#!/usr/bin/perl use strict; use warnings; # store 'A' and 'B' as a bitstream # (bit groups are stored big endian!) my @bits = ( 1, 0, 0, 0, 0, 0, 1, 0, # A / 0x41 / 0b01000001 0, 1, 0, 0, 0, 0, 1, 0, # B / 0x42 / 0b01000010 1, 1, 0, 0, 1, 0, 1 # incomplete byte ); my $data; while (@bits >= 8) { # fetch bit group my @eightbits_be = splice @bits, 0, 8; # convert to little endian my @eightbits_le = reverse @eightbits_be; # generate binary representation my $binary = '0b' . join q{}, @eightbits_le; # convert binary representation into actual value my $value = chr oct $binary; $data .= $value; } printf "data: %s\n", $data; # AB printf "bits: %s\n", join ', ', @bits; # 1, 1, 0, 0, 1, 0, 1
The generated/exprected output is:
data: AB
bits: 1, 1, 0, 0, 1, 0, 1

In reply to Optimize bit stream conversion by Monk::Thomas

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.