<?xml version="1.0" encoding="windows-1252"?>
<node id="620" title="How do I manipulate arrays of bits?" created="1999-10-07 20:20:52" updated="2005-08-15 07:33:39">
<type id="834">
perlfaq nodetype</type>
<author id="519">
faq_monk</author>
<data>
<field name="doctext">


&lt;P&gt;
Use 
&lt;CODE&gt;pack()&lt;/CODE&gt; and 
&lt;CODE&gt;unpack(),&lt;/CODE&gt; or else 
&lt;CODE&gt;vec()&lt;/CODE&gt; and the bitwise operations.

&lt;P&gt;
For example, this sets &lt;U&gt;$vec&lt;/U&gt; to have bit 
&lt;FONT SIZE=-1&gt;N&lt;/FONT&gt; set if $ints&amp;#091;N&amp;#093; was set:

&lt;P&gt;
&lt;PRE&gt;    $vec = '';
    foreach(@ints) { vec($vec,$_,1) = 1 }
&lt;/PRE&gt;
&lt;P&gt;
And here's how, given a vector in $vec, you can get those bits into your
&lt;CODE&gt;@ints&lt;/CODE&gt; array:

&lt;P&gt;
&lt;PRE&gt;    sub bitvec_to_list {
        my $vec = shift;
        my @ints;
        # Find null-byte density then select best algorithm
        if ($vec =~ tr/\0// / length $vec &amp;gt; 0.95) {
            use integer;
            my $i;
            # This method is faster with mostly null-bytes
            while($vec =~ /&amp;#091;^\0&amp;#093;/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 &amp;quot;b*&amp;quot;, $vec;
            push @ints, 0 if $bits =~ s/^(\d)// &amp;amp;&amp;amp; $1;
            push @ints, pos $bits while($bits =~ /1/g);
        }
        return \@ints;
    }
&lt;/PRE&gt;
&lt;P&gt;
This method gets faster the more sparse the bit vector is. (Courtesy of Tim
Bunce and Winfried Koenig.)

&lt;P&gt;
</field>
</data>
</node>
