in reply to Re: Optimize bit stream conversion
in thread Optimize bit stream conversion

Ah! That's nice.

I condensed it into:

#!/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 = pack "b*", join q{}, splice @bits, 0, -(@bits % 8); printf "data: %s\n", $data; # AB printf "bits: %s\n", join ', ', @bits; # 1, 1, 0, 0, 1, 0, 1

Update

Both variations do not convert properly if there actually isn't an incomplete byte. This version works:

# variant a) using floor() use POSIX; $data = pack 'b*', join q{}, splice @bits, 0, POSIX::floor(@bits / 8) +* 8; # variant b) using int $data = pack 'b*', join q{}, splice @bits, 0, int(@bits / 8) * 8;

Replies are listed 'Best First'.
Re^3: Optimize bit stream conversion
by choroba (Cardinal) on Jul 30, 2015 at 13:01 UTC
    I didn't want to confuse you with a terse code. Updated the original node with a correct solution.
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ