Stephen A. Jarjoura wrote:
...what if I had needed to store/retrieve some arbitrary number of bits?

Uri's suggestion of Bit::Vector is probably what you want, but more generally, take a look at the perlop man page and read up on the bitwise operators such as &, |, ^, and the shift operators <<, >>.



Here is a test case, I am wondering how some of you would address this challenge.
Store / Retrieve four (4) fields (2 bits, 6 bits, 3 bits, 5 bits) into 2 bytes
Example:
## bit string: 10 101010 110 01110
custom_pack(2,42,6,14) == \xAACE
custom_unpack(\xAACE) == (2,42,6,14)

# Retrieve four fields (2 bits, 6 bits, 3 bits, 5 bits) from 2 bytes sub custom_unpack { my $bits = shift;

    my @unpacked;
    push(@unpacked, ($bits & 0xC000) >> 14);
    push(@unpacked, ($bits & 0x3F00) >> 8);
    push(@unpacked, ($bits & 0x00E0) >> 5);
    push(@unpacked,  $bits & 0x001F);

    return @unpacked;
}

my $bits = 0xAACE; ## bit string: 10 101010 110 01110
print join(',',custom_unpack($bits)),"\n";


% perl bitshift.pl 2,42,6,14


-Tom

_______________________________________________
Boston-pm mailing list
[email protected]
http://mail.pm.org/mailman/listinfo/boston-pm

Reply via email to