Maybe not in one pass, since there's no way to unpack a 16-bit signed little-ending ints.

32-bit unsigned little-ending int: unpack('V', $_)
32-bit signed little-ending int: unpack('l', pack('L', unpack('V', $_)))
16-bit unsigned little-ending int: unpack('v', $_)
16-bit signed little-ending int: unpack('s', pack('S', unpack('v', $_)))

However, it's easy to have pack to most of the work, then just touch up the results elegantly.

$_ = "\x32\x54\x76\x98" # 2557891634 as a 32-bit unsigned LE int . "\x32\x54\x76\x98" # -1737075662 as a 32-bit signed LE int . "\x76\x98" # 39030 as a 16-bit unsigned LE int . "\x76\x98"; # -26506 as a 16-bit signed LE int my @nums = unpack('VVvv', $_); $_ = unpack('l', pack('L', $_)) for @nums[1]; # Fix signs of longs. $_ = unpack('s', pack('S', $_)) for @nums[3]; # Fix signs of shorts.

As for the bits, you didn't specify what you wanted to do with them, You could leave them grouped and use masks, or you could seperate them. The former is trivial (unpack('v', $_)). The latter is a bit more complicated, but not that much:

$_ = "\x34\x01"; my @nums = unpack('s', $_); my @flags = ( split //, unpack('B16', pack('n', $nums[0])) )[16-9 .. 1 +6-1];

Tested on a little-endian system, but it should work equally well on a big-endiang system.


In reply to Re: yet another "reading binary data" question by ikegami
in thread yet another "reading binary data" question by dwalin

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.