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: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); }
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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |