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;
In reply to Re^2: Optimize bit stream conversion
by Monk::Thomas
in thread Optimize bit stream conversion
by Monk::Thomas
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |