CGI/Perl Guide | Learning Center | Forums | Advertise | Login Site Search: in Perl Guide PerlGuru Forums Learning Ctr
 MAIN INDEX SEARCHPOSTS WHO'S ONLINE LOG IN

Home: Perl Programming Help: Frequently Asked Questions:
How do I manipulate arrays of bits?

Jasmine

Jan 19, 2001, 3:21 PM

Post #1 of 1 (3289 views)
 How do I manipulate arrays of bits? Can't Post
(From the Perl FAQ)

How do I manipulate arrays of bits?

Use pack() and unpack(), or else vec() and the bitwise operations.

For example, this sets \$vec to have bit N set if \$ints[N] was set:
 Code
`    \$vec = '';     foreach(@ints) { vec(\$vec,\$_,1) = 1 }`
And here's how, given a vector in \$vec, you can get those bits into your @ints array:
 Code
`    sub bitvec_to_list {         my \$vec = shift;         my @ints;         # Find null-byte density then select best algorithm         if (\$vec =~ tr/\0// / length \$vec > 0.95) {             use integer;             my \$i;             # This method is faster with mostly null-bytes             while(\$vec =~ /[^\0]/g ) {                 \$i = -9 + 8 * pos \$vec;                 push @ints, \$i if vec(\$vec, ++\$i, 1);                 push @ints, \$i if vec(\$vec, ++\$i, 1);                 push @ints, \$i if vec(\$vec, ++\$i, 1);                 push @ints, \$i if vec(\$vec, ++\$i, 1);                 push @ints, \$i if vec(\$vec, ++\$i, 1);                 push @ints, \$i if vec(\$vec, ++\$i, 1);                 push @ints, \$i if vec(\$vec, ++\$i, 1);                 push @ints, \$i if vec(\$vec, ++\$i, 1);             }         } else {             # This method is a fast general algorithm             use integer;             my \$bits = unpack "b*", \$vec;             push @ints, 0 if \$bits =~ s/^(\d)// && \$1;             push @ints, pos \$bits while(\$bits =~ /1/g);         }         return \@ints;     }`
This method gets faster the more sparse the bit vector is. (Courtesy of Tim Bunce and Winfried Koenig.)

 Announcements     PerlGuru Announcements Perl Programming Help     Frequently Asked Questions     Beginner     Intermediate     Advanced     Regular Expressions     mod_perl     DBI     Win32 Programming Help Fun With Perl     Perl Quizzes - Learn Perl the Fun Way     Perl Golf     Perl Poetry Need a Custom or Prewritten Perl Program?     I need a program that...     I Need a Programmer for Freelance Work     Throw Down The Gauntlet General Discussions     General Questions     Feedback     Tutorial/Article Suggestions for The Learning Cent     Internet Security Other Programming Languages     Javascript     PHP

 Search this forum this category all forums for All words Any words Whole Phrase (options) Powered by Gossamer Forum v.1.2.0