I have a single 8-bit byte ...
$item = 0x37; # ...or 00110111b

If I had to guess about what's ruining your day when you try to use vec() (and I do because you haven't shown us your code) I'd say you are getting confused by the way Perl handles numbers. Perl isn't C and $item = 0x37; is not a single byte like char item = 0x37; would be in C. It's two bytes: "55". To get a single byte use chr() or a string containing a single byte (like "\x37") instead.

$ perl -le 'print vec(0x37, $_, 1) for 0..7' # Ooops!!! $ perl -le 'print vec(chr(\x37), $_, 1) for 0..7' # Much better. $ perl -le 'print vec("\x37", $_, 1) for 0..7' # This works too.

Using unpack you have to jump through a few more hoops to get the same thing. You can unpack with a template of "b*" (or "B*" for reverse bit order) but that then gives you a string of 1s and 0s. You can unpack that with "c*" to get one value per bit... but the values won't be what you expect. Instead of "0"s and "1"s, you'll get "48"s and "49"s (i.e. ord("0") and ord("1").) So, to get the actual "0"s and "1"s you want, you have to then use chr(). Putting it all together gives something like this:

$ perl -le 'print for map chr, unpack "c*", unpack "b*", chr(0x37)'
Which gives the same output as the correct versions using vec() above. As you can see, this is exactly the kind of thing vec() was made for. You can make unpack do it, but it's not exactly the right tool for the job.

-sauoq
"My two cents aren't worth a dime.";

In reply to Re: Decoding Mapped Bitfields by sauoq
in thread Decoding Mapped Bitfields 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.