in reply to Decoding Mapped Bitfields

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.";

Replies are listed 'Best First'.
Re^2: Decoding Mapped Bitfields
by ozboomer (Friar) on Oct 09, 2005 at 13:14 UTC
    Ok, that was my downfall -- the chr() to turn a 16-bit int (under Win32 Perl) into a 'real' 8-bit byte.

    I did initially look at my C books as well as my Perl books to come up with the idea of using a bitfield in my application anyway. Just that I wasn't sure how to deal with it other than through the substr() approach (I've not really used vec() much, if at all, really).

    Still, I knew there had to be a simpler way...

    Many thanks for all your help, folks... 'tis greatly appreciated.