SPUG: Help with unpacking bit fields from binary data

Jody Magnuson jody at tc.fluke.com
Thu Jul 27 10:46:42 CDT 2000


I want to take binary data and unpack it into bit fields of various
lengths. In my example below, the first 6 bits (110011 or 51), the next
7 bits (0100001 or 33), and the last 3 bits (010 or 2).

I thought the following unpack command might work but this takes the
first 6 bits
of the first byte (51) and then the first 7 bits of the second byte (5)
and nothing goes into $c.

I could unpack it into one long binary string and then use substr to
extract the portions of interest but I was hoping there was a cleaner
way to do it. 

Thanks in advance for any help.

Jody Magnuson   e-mail: jody at tc.fluke.com  telephone: +1 425 446 5672
mail: Fluke Corporation / PO Box 9090 / Everett, WA 98206-9090 USA

#! /usr/local/bin/perl -w
use strict;

# from the Perl Cookbook
sub bin2dec {
    return unpack("N", pack("B32", substr("0" x 32 . shift, -32)));
}

my $binary = pack "B*", "1100110100001010";

# Why doesn't this work?
my ($a, $b, $c) = unpack("B6 B7 B3", $binary);
printf "a/b/c = %d %d %d\n", bin2dec($a), bin2dec($b), bin2dec($c);

 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
     POST TO: spug-list at pm.org       PROBLEMS: owner-spug-list at pm.org
      Subscriptions; Email to majordomo at pm.org:  ACTION  LIST  EMAIL
  Replace ACTION by subscribe or unsubscribe, EMAIL by your Email-address
 For full traffic, use spug-list for LIST ; otherwise use spug-list-digest
  Seattle Perl Users Group (SPUG) Home Page: http://www.halcyon.com/spug/





More information about the spug-list mailing list