SPUG: Help with unpacking bit fields from binary data

Ron Hartikka ronh at iainc.com
Thu Jul 27 13:36:09 CDT 2000


Can you use this?

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

my $binary = pack "B6B7B3", "110011", "0100001", "010";


# 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);

Seems like "The same template may generally also be used in the unpack
function." from the documentation of pack.



-----Original Message-----
From: owner-spug-list at pm.org [mailto:owner-spug-list at pm.org]On Behalf Of
Jody Magnuson
Sent: Thursday, July 27, 2000 11:47 AM
To: spug-list at pm.org
Subject: SPUG: Help with unpacking bit fields from binary data


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/




 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
     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