Monks,

I am writing some code that takes a number of pieces of data and packages them up into one large chunk. I am using pack to do this, and it works fine in most cases. E.g.,

my $eight_bit_piece = 255; my $other_eight_bit_piece = 255; my $sixteen_bit_piece = 8; my $packaged_data = pack("CCn", $eight_bit_piece, $other_eight_bit_piece, $sixteen_bit_piece); # Gives me 11111111 11111111 0000000000001000 as desired

However, I don't know what to do when my individual pieces of data don't divide cleanly into 8-bit chunks. For example, I want to assemble a 16-bit word from two six-bit and one four-bit chunks:

my $piece_one_six_bits = 12; # 001100 my $piece_two_six_bits = 12; # 001100 my $piece_three_four_bits = 5; # 0101 # What now?

I have come up with a solution...

my $packaged_data = pack("n", $piece_one_six_bits << (6 + 4) | $piece_two_six_bits << 4 | $piece_three_four_bits );
... but it doesn't feel right. I am trying to avoid bitwise operations. Isn't this work pack should be able to do? Can anybody point me in the right direction with this?

Thanks in advance for your help.


In reply to Using pack with data of odd lengths by crashtest

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.