I've used getc to read the byte stream and vec to test the first and second bits of the byte. Depending on the result of the tests I either just unpack an unsigned char or append one or two more getc() operations, mask off the first two bits and then either unpack() a network short (2 byte piece) or a left-padded with 8 0-bits network long (3 byte piece). I have not incorporated error checking for incomplete reads.

use strict; use warnings; use 5.010; my $mask2 = pack q{CC}, 0b00111111, 0b11111111; my $mask3 = pack q{CCC}, 0b00111111, 0b11111111, 0b11111111; my @packed = ( pack( q{C}, 0b01010101 ), pack( q{CC}, 0b10101010, 0b10101010 ), pack( q{CCC}, 0b11001100, 0b11001100, 0b11001100 ), ); my $byteStream = ( join q{}, @packed ) x 3; open my $byteStreamFH, q{<}, \ $byteStream or die $!; while ( defined( my $piece = getc( $byteStreamFH ) ) ) { unless ( vec $piece, 7, 1 ) { # 1 byte piece # say unpack q{C}, $piece; } elsif ( vec $piece, 6, 1 ) { # 3 byte piece # $piece .= getc( $byteStreamFH ) for 1 .. 2; $piece &= $mask3; say unpack q{N}, pack( q{C}, 0 ) . $piece; } else { # 2 byte piece # $piece .= getc( $byteStreamFH ); $piece &= $mask2; say unpack q{n}, $piece; } } close $byteStreamFH or die $!;

The output

85 10922 838860 85 10922 838860 85 10922 838860

I don't know how quick this would be on a large volume of data but I would imagine that a solution in C would be somewhat faster.

I hope this is of interest.

Cheers,

JohnGG


In reply to Re: [NOT] How would you decode this? by johngg
in thread [NOT] How would you decode this? by BrowserUk

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.