For purposes like this I am keeping a pair of functions in a private utility library (somewhat simplified):
sub str_from_bits { my $vec = ''; vec( $vec, $_, 1) = 1 for @_; $vec; } sub str_to_bits { my $vec = shift; grep vec( $vec, $_, 1), 0 .. 8*( length $vec); }
str_from_bits() constructs a bit vector from a list of integers that are the indices of the one-bits in the string. str_to_bits() does the reverse. The function str_from_bits() applies directly to your problem:
my $vec = str_from_bits( 8, 1, 9); my ( $lo, $hi) = ( vec( $vec, 0, 8), vec( $vec, 1, 8)); printf "lo: 0x%02x, hi: 0x%02x\n", $lo, $hi;

The functions above are slightly simplified. There is also a num_from_bits() that returns an integer instead of a bit string. There would also be num_to_bits()<c>, but that is unified with <c>str_to_bits() as just to_bits() which checks its argument whether it's a string or number, similar to the bitwise boolean operators.

Together these functions cover most needs for bit manipulation that come up.

Anno


In reply to Re: Making two 8-bit numbers from indices of set bits by Anno
in thread Making two 8-bit numbers from indices of set bits by carcassonne

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.