Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: Unpacking variable length bit fields

by ikegami (Pope)
on Jun 18, 2012 at 21:27 UTC ( #976907=note: print w/replies, xml ) Need Help??


in reply to Unpacking variable length bit fields

If your lengths aren't necessarily multiples of 8,
my @fields; my $bits = unpack('B*', $input); while ($bits) { die if length($bits) < 8; my $num_bits = unpack('C', pack('B*', substr($bits, 0, 8, ''))); my $field = substr($bits, 0, $num_bits, ''); push @fields, $field; }

You can probably do this more efficiently using bit twiddling, but this is simpler.

If you want the result as a number rather than a string of "1"s and "0"s, you can use the following:

use Config qw( ); use constant UV_BITS => $Config::Config{uvsize} * 8; die if $num_bits > UV_BITS; push @fields, pack('B*', substr(("0" x UV_BITS).$field, -UV_BITS));

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://976907]
help
Chatterbox?
[atcroft]: PriNet: Those code bits worked for me, with test hashes, but I didn't test it with more than a few simple test cases. *shrug* Had hoped it would help, at least.

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (5)
As of 2017-06-28 03:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    How many monitors do you use while coding?















    Results (619 votes). Check out past polls.