OK, I admit it... pack and unpack confuse me... each time I think I have them figured out, I realize I really don't. Are there any resources (other then perldoc -f unpack) with some more advanced examples?

The particular problem I'm having at the moment is unpacking a C struct like this:

struct { unsigned long var1:16, var2:16; unsigned long var3:24, var4:8; unsigned long var5:6, var6:26; };

The first 2, I got (I think), the second 2 I THOUGHT I got, but was wrong.. the last 2... well, frankly I'm just not too sure. Here's what I tried:

$fh->read($buf, 12); @var = unpack("s s C3 C b6 b26", $buf);

Now, $var[0] and $var[1] end up as 2 byte shorts (as I expected), $var[2] ends up as 1 byte, not the 3 bytes I was expecting... it looks like the 2nd and 3rd bytes are put into $var[3] and $var[4]... which of course throws the rest off track.

How do I grab 3 bytes and put that into a single var, not split into 3 separate vars?

With regards to the "b6" and "b26"... well... I don't really want the value returned as binary data... I just want a 6 bit integer and a 26 bit integer respectively. How do I do that?


In reply to Unpacking struct by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.