Here is one way to do it (but you aren't going to like it!):

print unpack 'C*', pack '(B8)*', map{ substr '00000000'.$_, -8 } unpack 'A1A3A4',unpack 'B*',pack 'C', 162;; 1 2 2

To explain that, (right-to-left):

## pack 162 into an 8-bit binary value (a char). pack 'C', 162 ## unpack that into it's bits, (asciized binary bitstring). unpack 'B*', ## split that into the 3 fields. ('1','010', '0010' ). unpack 'A1A3A4', ## Pad each to the smallest size (8 bits) that Perl can deal with nume +rically. map{ substr '00000000'.$_, -8 } ## Pack them back up to binary values (chars). pack '(B8)*', ## And unpack them back to numeric values. unpack 'C*', ## and convert those to ascii-decimal for display print

The problem with vec is that it only allows you to deal with bits in quantites that are powers of 2, and on powers of two boundaries, which makes dealing with your 3-bit field problematic.

Probably easier to use is a subroutine like this:

#! perl -slw use strict; sub bitField { my( $value, $offset, $size ) = @_; my $mask = ( ( 1<<$size) - 1 ) << $offset; return ( $value & $mask ) >> $offset; } print bitField 162, 7, 1; print bitField 162, 4, 3; print bitField 162, 0, 4; __END__ P:\test>499354 1 2 2

Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
"Science is about questioning the status quo. Questioning authority".
The "good enough" maybe good enough for the now, and perfection maybe unobtainable, but that should not preclude us from striving for perfection, when time, circumstance or desire allow.

In reply to Re: Extracting Bit Fields (Again) by BrowserUk
in thread Extracting Bit Fields (Again) by ozboomer

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.