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
The generated/exprected output is:#!/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
data: AB bits: 1, 1, 0, 0, 1, 0, 1
In reply to Optimize bit stream conversion by Monk::Thomas
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |